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

北城以北 提交于 2021-02-07 18:15:51

问题


I need to write a bash script to do something as another user and then return to the initial user...

Suppose I run the following as root:

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

In the console I should write "exit", but in bash is a keyword and it exits the script...

Thanks in advance,


回答1:


Use su -c. From 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.



回答2:


The simplest way is to make the stuff that has to run as the other user a separate script and invoke it with the "-c" option in su, like su -c otherscript userid.

You may be able to do that as a "here script" with << EOF, but I've never tried it.




回答3:


You could also use sudo.




回答4:


This will do it.

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



来源:https://stackoverflow.com/questions/2538624/how-to-login-as-another-user-and-then-log-out-in-bash-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!