Preserving quotes in bash function parameters

后端 未结 8 823
天涯浪人
天涯浪人 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:28

    I was in a similar position to you in that I needed a script to wrap around an existing command and pass arguments preserving quoting.

    I came up with something that doesn't preserve the command line exactly as typed but does pass the arguments correctly and show you what they were.

    Here's my script set up to shadow ls:

    CMD=ls
    PARAMS=""
    
    for PARAM in "$@"
    do
      PARAMS="${PARAMS} \"${PARAM}\""
    done
    
    echo Running: ${CMD} ${PARAMS}
    bash -c "${CMD} ${PARAMS}"
    echo Exit Code: $?
    

    And this is some sample output:

    $ ./shadow.sh missing-file "not a file"
    Running: ls "missing-file" "not a file"
    ls: missing-file: No such file or directory
    ls: not a file: No such file or directory
    Exit Code: 1
    

    So as you can see it adds quotes which weren't originally there but it does preserve arguments with spaces in which is what I needed.

提交回复
热议问题