【问题标题】:Properly quote args for calling su -c正确引用参数以调用 su -c
【发布时间】:2014-04-04 14:32:44
【问题描述】:

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"

【问题讨论】:

    标签: shell su


    【解决方案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 "$@")"
    

    【讨论】:

      猜你喜欢
      • 2012-09-02
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      • 1970-01-01
      • 2019-07-04
      • 2019-05-13
      • 1970-01-01
      相关资源
      最近更新 更多