How can I escape an arbitrary string for use as a command line argument in Bash?

后端 未结 8 1764
时光说笑
时光说笑 2020-12-08 13:44

I have a list of strings and I want to pass those strings as arguments in a single Bash command line call. For simple alphanumeric strings it suffices to just pass them verb

8条回答
  •  遥遥无期
    2020-12-08 14:13

    If you want to securely quote anything for Bash, you can use its built-in printf %q formatting:

    cat strings.txt:

    yes
    no
    Hello, world
    C:\Program Files\
    "
    \
    \\
    \\\
    \\\\
    \\\\\
    "\
    "\T
    "\\T
    !1
    !A
    "!\/'"
    "Jeff's!"
    $PATH
    %PATH%
    &
    <>|&^
    *@$$A$@#?-_
    

    cat quote.sh:

    #!/bin/bash
    while IFS= read -r -d $'\n'
    do
        printf %q "$REPLY"
        printf '\n'
    done < strings.txt
    

    ./quote.sh:

    yes
    no
    Hello\,\ world
    C:\\Program\ Files\\
    \"
    \\
    \\\\
    \\\\\\
    \\\\\\\\
    \\\\\\\\\\
    \"\\
    \"\\T
    \"\\\\T
    \!1
    \!A
    \"\!\\/\'\"
    \"Jeff\'s\!\"
    \$PATH
    %PATH%
    \&
    \<\>\|\&\^
    \*@\$\$A\$@#\?-_
    

    These strings can be copied verbatim to for example echo to output the original strings in strings.txt.

提交回复
热议问题