Bash quoted array expansion

前端 未结 6 963
借酒劲吻你
借酒劲吻你 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:23

    bash's printf command has a %q format that adds appropriate quotes to the strings as they're printed:

    echo "Failed: foo:$(printf " %q" "${mycmd[@]}")"
    

    Mind you, its idea of the "best" way to quote something isn't always the same as mine, e.g. it tends to prefer escaping funny characters instead of wrapping the string in quotes. For example:

    crlf=$'\r\n'
    declare -a mycmd=( command.ext "arg1 with space 'n apostrophe" "arg2 with control${crlf} characters" )
    echo "Failed: foo:$(printf " %q" "${mycmd[@]}")"
    

    Prints:

    Failed: foo: command.ext arg1\ with\ space\ \'n\ apostrophe $'arg2 with control\r\n characters'
    

提交回复
热议问题