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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With