正确引用调用su -c的args

时间:2014-04-04 14:32:45

标签: shell su

su -c接受一个字符串参数,传递给$SHELL -c。如果手动完成,这会使更复杂的命令成为引用噩梦。我想要的是:将"$@"转换为一个字符串的函数,由目标shell适当地解析。为简单起见,我们假设目标shell与当前shell相同,或者简单(b)ash。

# Naive implementation:
run_su() {
  /bin/sh -c "$*"
  # To emulate su targetuser -c
}
run_su echo "double  spaces"
# Output: double spaces
# NOte the missing double space

我知道sudo会以正确的方式做到这一点。但我不想依赖sudo,除非我们绝对必须这样做。

# This does the right thing
run_sudo() {
    sudo -u targetuser "$@"
}
run_sudo echo "double  spaces"

1 个答案:

答案 0 :(得分:1)

如果你可以假设bash,那很简单:

/bin/bash -c "$(printf "%q " "$@")"

对于POSIX sh:

quote() {
  for arg
  do
    var=$(printf "%sx" "$arg" | sed -e "s/'/'\\\\''/")
    var=${var%x}
    printf "'%s' " "$var"
  done
}
/bin/sh -c "$(quote "$@")"