0

How to solve below problem.

myscript.sh
echo First argument: $1
echo Second argument: $2
for i in $* do
echo $i
done

now executing the script:

$./myscript.sh "this is" value
First argument: this is
Second argument: value

this
is
value

When I am printing $1 I am getting the value "this is" but inside loop first argument coming as "this"

I want when the loop execute it will print

this is 
value 

1 Answers1

2

This is due to the usage of $* instead of "$@" to get all of the arguments. From ShellCheck:

$*, unquoted, is subject to word splitting and globbing.

Let's say you have three arguments: baz, foo bar and *

"$@" will expand into exactly that: baz, foo bar and *

$* will expand into multiple other arguments: baz, foo, bar, file.txt and otherfile.jpg

For the desired behavior you can do this:

echo "First argument: $1"
echo "Second argument: $2"

for i in "$@"
    do echo "$i"
done
Marcus
  • 3,216
  • 2
  • 22
  • 22