0

Got some odd behaviour coming out of a bash script

myscript.sh

#! /bin/bash
# Demo bash script
for i in $@
do
   echo $i
done
echo $# args

if I execute it thus:

myscript.sh "Arg 1" "Arg 2"

Result:

Arg
1
Arg
2
2 args

So it's calculating the correct number of args but processing them wrong or more to the point I'm processing them wrong

Any thoughts?

Big Ian
  • 163
  • 3
  • 12
  • 1
    Run your code through http://shellcheck.net and it'll identify this and other issues automatically. – Charles Duffy Jun 09 '20 at 12:21
  • 1
    BTW, same thing applies to the `echo`, which should use `"$i"`; see [I just assigned a variable, but `echo $variable` shows something else!](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else), and [BashPitfalls #14](https://mywiki.wooledge.org/BashPitfalls#echo_.24foo). – Charles Duffy Jun 09 '20 at 12:25

1 Answers1

1

Change

for i in $@

to

for i in "$@"

in order to apply correctly parameter expansion.

samthegolden
  • 1,366
  • 1
  • 10
  • 26