build argument lists containing whitespace

前端 未结 5 1505
一生所求
一生所求 2020-12-01 13:24

In bash one can escape arguments that contain whitespace.

foo \"a string\"

This also works for arguments to a command or function:

5条回答
  •  天命终不由人
    2020-12-01 13:57

    There are (at least) two ways to do this:

    1. Use an array and expand it using "${array[@]}":

      bar() {
          local i=0 args=()
          for arg in "$@"
          do
              args[$i]="prefix $arg"
              ((++i))
          done
      
          foo "${args[@]}"
      }
      

      So, what have we learned? "${array[@]}" is to ${array[*]} what "$@" is to $*.

    2. Or if you do not want to use arrays you need to use eval:

      bar() {
          local args=()
          for arg in "$@"
          do
              args="$args \"prefix $arg\""
          done
      
          eval foo $args
      }
      

提交回复
热议问题