[英]Emulating sudo's behaviour with su
I'm trying to write a wrapper around su
to make it more like sudo
, so that su_wrapper foo bar baz
== su -c "foo bar baz"
. 我正在尝试在
su
周围写一个包装器使它更像sudo
,所以su_wrapper foo bar baz
== su -c "foo bar baz"
。
However, I'm not sure how to approach this problem. 但是,我不确定如何解决这个问题。 I came up with this:
我想出了这个:
su_wrapper ()
{
su -c "$@"
}
However, in the above, only a single argument can be there; 但是,在上面,只有一个参数可以存在; this fails with multiple arguments (as
su
sees them as its own arguments). 这失败了多个参数(因为
su
将它们视为自己的参数)。
There's also another problem: since the argument is passed through the shell, I think I must explicitly specify the shell to avoid other problems. 还有另一个问题:由于参数是通过shell传递的,我认为我必须明确指定shell以避免其他问题。 Perhaps what I want to do could be expressed in pseudo-bash(!) as
su -c 'bash -c "$@"'
. 也许我想做的事情可以用伪bash(!)表示为
su -c 'bash -c "$@"'
。
So, how could I make it accept multiple arguments? 那么,我怎么能让它接受多个参数呢?
Use printf "%q"
to escape the parameters so they can be used as string input to your function: 使用
printf "%q"
来转义参数,以便它们可以用作函数的字符串输入:
su_wrapper() {
su -s /bin/bash -c "$(printf "%q " "$@")"
}
Unlike $*
, this works even when the parameters contain special characters and whitespace. 与
$*
不同,即使参数包含特殊字符和空格,这也适用。
You need $*
and not $@
: 你需要
$*
而不是$@
:
su_wrapper() {
local IFS=' '
su -c "$*"
}
See the Special Parameters section in the Bash Reference Manual for the difference between $*
and $@
. 有关
$*
和$@
之间的区别,请参阅“ Bash参考手册”中的 “ 特殊参数”部分 。
I added local IFS=' '
just in case IFS
is set to something else (after reading what $*
does, it should be clear why you want to make sure that IFS
is set to a space). 我添加了
local IFS=' '
以防IFS
被设置为其他东西(在阅读$*
之后,应该清楚为什么要确保IFS
设置为空格)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.