0

I concat all the arguments in a variable $ARGS and pass all of them to a command onece togather, just like what the ./test_arg.sh do.

But i found that the arguments with quoted string was splitted into multiple ones.

Here is my test scripts, test_arg.sh perform the test case and arg.sh just print every argument on seperated line.

$ cat ./test_arg.sh 
#!/bin/sh

ARGS="$ARGS OPT_1"
ARGS="$ARGS OPT_2"
ARGS="$ARGS 'OPT_3 is a string with space'"

echo "./arg.sh $ARGS"

echo '----------------------------'

./arg.sh $ARGS
[ xiafei@xiafeitekiMacBook-Pro ~/tmp ]
$ cat ./arg.sh 
#!/bin/sh

for var in "$@"
do
    echo "arg -> $var"
done

Here coms the result:

$ ./test_arg.sh
./arg.sh  OPT_1 OPT_2 'OPT_3 is a string with space'
----------------------------
arg -> OPT_1
arg -> OPT_2
arg -> 'OPT_3
arg -> is
arg -> a
arg -> string
arg -> with
arg -> space'

But if I put argument directly after the command it works correctly:

$ cat test_arg.sh 
#!/bin/sh
./arg.sh OPT_1 OPT_2 'OPT_3 is a string with space'

[ xiafei@xiafeitekiMacBook-Pro ~/tmp ]
$ sh test_arg.sh 
arg -> OPT_1
arg -> OPT_2
arg -> OPT_3 is a string with space

I guess the problem is the way bash process quotes. Anyone knows about it?

qiuxiafei
  • 5,827
  • 5
  • 30
  • 43

1 Answers1

0

The way the unix shell works, your call to ./arg.sh $ARGS will not evalutate the ' quotes.

One possible solution is to use eval "./arg.sh $ARGS".

Lars Brinkhoff
  • 13,542
  • 2
  • 28
  • 48
  • 1
    If one of your arguments is the name of a file called `/tmp/im-evil/$(rm -rf /*)/hello.txt`, using `eval` in this way would be a very, *very* bad idea. – Charles Duffy Nov 16 '16 at 16:32