How to log in as another user and then log out in a bash script?

I need to write a bash script to do something different and then return to the original user ...

Suppose I run as root:

#!/bin/bash USER=zaraza su - "${USER}" #do some stuff as zaraza ________ #here I should logout zaraza #continue doing things as root 

I have to write "exit" in the console, but there is a keyword in bash and it exits the script ...

Thanks in advance,

+4
source share
4 answers

Use su -c . On the man page:

  su man -c catman Runs the command catman as user man. You will be asked for man's password unless your real UID is 0. 
+5
source

The easiest way is to make the material that should be run as another user a separate script and invoke it using the -c option in su, for example, su -c otherscript userid .

You can do this as a โ€œhere scriptโ€ with << EOF , but I have never tried it.

+3
source

You can also use sudo .

0
source

It will do it.

su - $ {username} -c / path / to / the / shellscript.sh

0
source

Source: https://habr.com/ru/post/1305456/


All Articles