简体   繁体   中英

escaping sh/bash function arguments

I want to submit multiple commands with arguments to shell functions, and thus quote my commands like his:

$ CMD=''\''CMD'\'' '\''ARG1 ARG2 ARG3'\'''
$ echo $CMD
'CMD' 'ARG1 ARG2 ARG3' 'ARG4'

Now when I try to us them in a function like this:

$ function execute { echo "$1"; echo "$2"; echo "$3"; }

I get the result:

$ execute $CMD
'CMD'
'ARG1
ARG2

How can I get to this result:

$ execute $CMD
CMD
ARG1 AGR2 ARG3

Thanks in advance!

PS: I use an unquoting function like:

function unquote { echo "$1" | xargs echo; }

EDIT:

to make my intentions more clear: I want to gradually build up a command that needs arguments with spaces passed to subfunctions:

$ CMD='HOST '\''HOSTNAME'\'' '\''sh SCRIPTNAME'\'' '\''MOVE '\''\'\'''\''/path/to/DIR1'\''\'\'''\'' '\''\'\'''\''/path/to/DIR2'\''\'\'''\'''\'''
$ function execute { echo "$1 : $2 : $3 : $4"; }
$ execute $CMD
HOST : 'HOSTNAME' : 'sh : SCRIPTNAME'

The third arguments breaks unexpected at a space, the quoting is ignored. ??

Use an array and @ in double quotes:

function execute () {
    echo "$1"
    echo "$2"
    echo "$3"
}

CMD=('CMD' 'ARG1 ARG2 ARG3' 'ARG4')
execute "${CMD[@]}"
function execute { 
  while [[ $# > 0 ]]; do
      cmd=$(cut -d' ' -f1 <<< $1)
      arg=$(sed 's/[^ ]* //' <<< $1)
      echo "$cmd receives $arg"
      shift
  done
}

CMD1="CMD1 ARG11 ARG12 ARG13"
CMD2="CMD2 ARG21 ARG22 ARG23"
execute "$CMD1" "$CMD2"

Gives:

CMD1 receives ARG11 ARG12 ARG13
CMD2 receives ARG21 ARG22 ARG23

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM