在linux脚本中更改用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10227590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:52:56  来源:igfitidea点击:

change user in linux script

linuxsh

提问by Chuck

User x run a script. Now I want to change the user in the script to User y.

用户 x 运行脚本。现在我想将脚本中的用户更改为用户 y。

#!/bin/sh
whoami
echo password | su y
whoami

But I get this:

但我明白了:

x
su: must be run from a terminal
x

Thanks for your help.

谢谢你的帮助。

回答by pikzen

Su cannot be ran in a Bash script. You can use sudo -u <user> <command> &&however.

Su 不能在 Bash 脚本中运行。sudo -u <user> <command> &&但是你可以使用。

回答by gerritjvv

you can do:

你可以做:

su - $USER -l -m -c $CMD

su - $USER -l -m -c $CMD

-l provide an environment similar to the login env -m preserves the current environment -c runs the command

-l 提供类似于登录的环境 env -m 保留当前环境 -c 运行命令

e.g. I use this to run nohup commands also

例如,我也用它来运行 nohup 命令

su - $USER -l -m -c "nohup $RUN_CMD > "$LOG" 2>&1 >> /dev/null&"

su - $USER -l -m -c "nohup $RUN_CMD > "$LOG" 2>&1 >> /dev/null&"

回答by francoisrv

This is working for me inside a bash script:

这在 bash 脚本中对我有用:

whoami;
sudo su $user << BASH
  whoami;
BASH