在脚本中从 sudo 转义

Escaping from sudo within a script

我有一个脚本将另一个脚本调用为 sudo。在第二个脚本中,我希望能够 运行 另一个进程 没有 sudo 权限(有问题的进程是 brew,它不能很好地播放sudo).

这是有问题的代码:

scriptA.sh:

#!/bin/sh

sudo ./scriptB.sh

scriptB.sh:

#!/bin/sh

# This runs as sudo, but I need it to run as a regular user e.g. `username`
brew update

我尝试了 su -c "brew update" -s /bin/sh username,但是 OS X 的 su 不允许 c 标志。

再用sudo :

sudo -u username brew update

超级用户可以使用su 命令成为任何其他用户。所以

su otheruser -c "command to execute"

OS X su 确实允许 -c 选项。您只需要将其放在用户名之后即可。来自手册页:

If the optional args are provided on the command line, they are passed to the login shell of the target login. Note that all command line arguments before the target login name are processed by su itself, everything after the target login name gets passed to the login shell.

在这种情况下,-c 不是 su 命令的选项,它是登录 shell 的选项。大多数 shell 都采用 -c 选项来指定要执行的命令。