如何在 bash 脚本中切换/更改用户 ID 以在同一脚本中执行命令?

a1a*_*1an 17 sudo bash bash-scripting

有没有办法在脚本中切换用户身份(作为安装过程的一部分以 root 身份执行)以执行某些命令而不调用外部脚本,然后返回root运行其他命令?

有点:

#!/bin/bash
some commands as root
SWITCH_USER_TO user
some commands as user including environment variables checks, without calling an external script
SWITCH_USER_BACK
some other stuff as root, maybe another user id change...
Run Code Online (Sandbox Code Playgroud)

Ign*_*ams 32

不,但是您可以使用sudo运行 shell 并使用 heredoc 为其提供命令。

#!/bin/bash
whoami
sudo -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami
Run Code Online (Sandbox Code Playgroud)