5

I want to pass a string as command line argument to a bash script; Simply my bash script is:

>cat test_script.sh

for i in $*
do 
echo $i
done

I typed

bash test_script.sh test1 test2 "test3 test4"

Output :

test1
test2
test3
test4

Output I am expecting:

test1
test2
test3 test4

I tried with backslashes (test1 test2 "test3\ test4") and single quotes but I haven't got the expected result.

How do I get the expected output?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
sivakumarspnv
  • 51
  • 1
  • 1
  • 3

2 Answers2

8

You need to use:

for i in "$@"
do echo $i
done

or even:

for i in "$@"
do echo "$i"
done

The first would lose multiple spaces within an argument (but would keep the words of an argument together). The second preserves the spaces in the arguments.

You can also omit the in "$@" clause; it is implied if you write for i (but personally, I never use the shorthand).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
-1

Try use printf

for i in $* do $(printf '%q' $i) done
Danny Hong
  • 1,474
  • 13
  • 21