Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a string as command line argument for bash script? [duplicate]

Tags:

bash

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?

like image 494
sivakumarspnv Avatar asked Nov 01 '12 11:11

sivakumarspnv


1 Answers

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

like image 65
Jonathan Leffler Avatar answered Oct 29 '22 05:10

Jonathan Leffler