Preserving quotes in bash function parameters

后端 未结 8 812
天涯浪人
天涯浪人 2020-12-05 05:13

What I\'d like to do is take, as an input to a function, a line that may include quotes (single or double) and echo that line exactly as it was provided to the function. For

8条回答
  •  执念已碎
    2020-12-05 05:21

    Although @Peter Westlake's answer is correct, and there are no quotes to preserve one can try to deduce if the quotes where required and thus passed in originally. Personally I used this requote function when I needed a proof in my logs that a command ran with the correct quoting:

    function requote() {
        local res=""
        for x in "${@}" ; do
            # try to figure out if quoting was required for the $x:
            grep -q "[[:space:]]" <<< "$x" && res="${res} '${x}'" || res="${res} ${x}"
        done
        # remove first space and print:
        sed -e 's/^ //' <<< "${res}"
    }
    

    And here is how I use it:

    CMD=$(requote "${@}")
    # ...
    echo "${CMD}"
    

提交回复
热议问题