且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

bash:如何打印和运行其中包含管道运算符|的cmd数组

更新时间:2023-10-17 16:44:04

如果要将仅包含|的数组元素视为生成管道的指令,则可以这样做。我不建议使用--这意味着如果您不验证字符串中的变量不能只由单个管道字符组成,就会有安全风险--但这是可能的。

下面,我们创建了一个随机单次使用信号,以使攻击更加困难。如果您不愿意这样做,请将[[ $arg = "$pipe" ]]更改为[[ $arg = "|" ]]
# generate something random to make an attacker's job harder
pipe=$(uuidgen)

# use that randomly-generated sigil in place of | in our array
cmd_array=(
  ls -a /
  "$pipe" grep "home"
)

exec_array_pipe() {
  local arg cmd_q
  local -a cmd=( )
  while (( $# )); do
    arg=$1; shift
    if [[ $arg = "$pipe" ]]; then
      # log an eval-safe copy of what we're about to run
      printf -v cmd_q '%q ' "${cmd[@]}"
      echo "Starting pipeline component: $cmd_q" >&2
      # Recurse into a new copy of ourselves as a child process
      "${cmd[@]}" | exec_array_pipe "$@"
      return
    fi
    cmd+=( "$arg" )
  done
  printf -v cmd_q '%q ' "${cmd[@]}"
  echo "Starting pipeline component: $cmd_q" >&2
  "${cmd[@]}"
}

exec_array_pipe "${cmd_array[@]}"

查看在https://ideone.com/IWOTfO

的在线沙箱中运行