![](/img/trans.png)
[英]How do I execute a "runuser" command, with arguments, in a bash script?
[英]How do I execute the arguments to a bash function as root using the su command?
我正在编写一个脚本,其中我有一个 function 以 root 身份运行命令。 这样它就可以根据用户安装的内容使用 sudo、doas 或 su。 function 看起来像这样:
as_root() {
# $SU_CMD contains either sudo, doas --, or nothing
if [[ -n $SU_CMD ]]; then
$SU_CMD $@
else
su root -- $@
fi
}
如果 sudo 和 doas 都不可用,这将不起作用。 su root -- <command>
不是以 root 身份执行命令,而是写入/usr/bin/<command>: /usr/bin/<command>: cannot execute binary file
to the terminal。 我还尝试su -c "$@"
以及其他组合,但没有骰子。
我将如何 go 关于执行 arguments 到 bash ZC1C425268E683854F1AB5074Csu17 ZC1C425268E683854F1AB5074Csu17?
您可能要运行三个命令。 请注意,在所有三种情况下都建议使用--
。
sudo -- "$@"
doas -- "$@"
su root -- "$@"
由于 function 的名称意味着您始终需要su root
(而不是su foo
或其他用户),因此要求root
包含在SU_CMD
中是没有意义的。 因此,您可以简单地编写
as_root () {
case $SU_CMD in
sudo) sudo -- "$@" ;;
doas) doas -- "$@" ;;
su) su root -- -c "$*" ;;
*) printf 'Invalid choice: %s\n' "$SU_CMD" >&2 ;;
esac
}
(这可以重构,但考虑到 function 的简单性,这似乎不值得付出努力。)
使用单个破折号而不是两个或更好的 -l 以避免混淆:
as_root() {
if [[ -n $SU_CMD ]]; then
$SU_CMD "$@";
else
su root -l -c "$@";
fi
}
morbeo@pc:~$ as_root whoami
Password:
root
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.