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?

1
  • 2
    Aren't Output and expected Output same? Commented Nov 1, 2012 at 11:07

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

-1

Try use printf

for i in $* do $(printf '%q' $i) done

2 Comments

That won't work while you use $*; you have to use "$@", explicitly or implicitly.
a fuller explanation might help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.