如何在Bash脚本中以另一个用户身份登录,然后退出登录?

5

我需要编写一个bash脚本,以另一个用户的身份执行某些操作,然后返回到初始用户...

假设我以root身份运行以下命令:

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

在控制台中,我应该写“exit”,但在bash中,“exit”是一个关键字,它会退出脚本...
提前致谢,
4个回答

6
使用 su -c 命令。从 man 页面中得知:
 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.

4

最简单的方法是将必须以其他用户身份运行的内容作为一个独立脚本,并使用su命令中的"-c"选项调用它,比如 su -c otherscript userid

你也可以尝试使用“here script”,使用 << EOF,但我从未尝试过。


0

你也可以使用sudo


0

这样做就可以了。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接