Bash quoted array expansion

前端 未结 6 943
借酒劲吻你
借酒劲吻你 2021-01-31 02:57

WHen I write a bash program I typically construct calls like follows:

declare -a mycmd=( command.ext \"arg1 with space\" arg2 thing etc )

\"${mycmd[@]}\" || ech         


        
6条回答
  •  深忆病人
    2021-01-31 03:14

    A cumbersome method (which only quotes arguments that contain spaces):

    declare -a myargs=(1 2 "3 4")
    for arg in "${myargs[@]}"; do
        # testing if the argument contains space(s)
        if [[ $arg =~ \  ]]; then
          # enclose in double quotes if it does 
          arg=\"$arg\"
        fi 
        echo -n "$arg "
    done
    

    Output:

    1 2 "3 4"
    

    By the way, with regards to quoting is lost on this pass, note that the quotes are never saved. " " is a special character that tells the shell to treat whatever is inside as a single field/argument (i.e. not split it). On the other hand, literal quotes (typed like this \") are preserved.

提交回复
热议问题