我有一个 shell 脚本,其中大多数命令需要在sesu
用户下运行,然后我需要以当前用户身份运行一些命令。你能帮我吗?
答案1
如果不想每次都指定密码,请添加sesu
到sudoers
组并运行您想要的命令:
sudo su -c "command string"
此方式command string
以超级用户(root等)身份运行。
答案2
命令
exit
关闭当前 shell。如果你正在运行类似 userX,然后切换到用户是,出口关闭你所在的外壳是并让你回到X
答案3
答案4
我最近也遇到过类似的情况。以下是我在调用脚本时立即进入超级用户级别,然后执行普通用户任务的方法。我认为这可能有助于您找到获得所需解决方案的方法:
#!/bin/bash
# generic_sudo.sh
# Tool that demonstrates in-then-out of sudo
# This demo is pointless if called with 'sudo generic_sudo.sh'
# Need root priviledges for some superuser work
if (( EUID != 0 )); then # If the user is not "root":
# In general one should use ((..)) for testing numbers and integer variables, and [[..]] for testing strings and files.
sudo $0 # Relaunch it as "root".
EXITCODE=$?
printf "su mode OFF.\n" # If we got here, we left superuser mode
printf "EUID is: %d\n" $EUID
printf "Exit code %d\n" $EXITCODE
exit $EXITCODE # Once it finishes, exit gracefully.
else
printf "su mode ON.\n"
fi # End if.
printf "EUID is: %d\n" $EUID
# Some superuser work
printf "Some superuser work was done.\n"
exit 0