jlue
jlue

Reputation: 35

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. ??

Upvotes: 1

Views: 121

Answers (2)

perreal
perreal

Reputation: 97918

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

Upvotes: 2

choroba
choroba

Reputation: 241768

Use an array and @ in double quotes:

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

CMD=('CMD' 'ARG1 ARG2 ARG3' 'ARG4')
execute "${CMD[@]}"

Upvotes: 5

Related Questions