有没有办法在脚本中切换用户身份(作为安装过程的一部分以 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...
答案1
不可以。但是您可以用sudo
它来运行 shell 并使用 heredoc 来向其提供命令。
#!/bin/bash
whoami
sudo -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami