Sometimes shell scripts just don't work the way you think they should, or you get strange
error messages when running your script. Just remember: The computer is always right.
It's easy to omit a significant blank, quotation mark, or bracket, or to mistakenly use a
single quotation mark when you should have used double quotation marks or a backtick.
count=1
until [ "$*" = "" ]
do
echo "Arg $count : $1 "
shift
count=$count+1
done
At first glance, it looks golden, but for some reason the counter is not incrementing properly. Try running it with the command
% bash -x listarg abc def
and look at the trace output as the shell executes. The lines prefixed with a plus sign show the progress of the running script, and the lines without the plus sign are the script's normal output.
+ count=1
+ [ abc def = ]
+ echo Arg 1 : abc
Arg 1 : abc
+ shift
+ count=1+1 Hmmm . . .
+ [ def = ]
+ echo Arg 1+1 : def
Arg 1+1 : def Not Good!
+ shift
+ count=1+1+1
+ [ = ]
Instead of printing Arg 2 : def, we got Arg 1+1 : def. But the trace output line reading count=1+1 nails the problem. You forgot to use the expr command, so the shell is treating this as a string concatenate instead of a mathematical calculation.
Note: You can always press Ctrl-C to stop a running shell script. This is handy if you accidentally create a script with an infinite loop (one that will never end by itself).
Previous Lesson: Shell Script Looping
Next Lesson: Perl Basics
Comments (most recent first)
John Ndambuki (29 Jul 2010, 16:41)
+ An alternative solution: Solution #3 ----------- count=1 until [ "$*" = "" ] do echo "Arg $count : $1 " shift count=$(($count+1)) done
John Ndambuki (29 Jul 2010, 04:41)
Just adding 2 more solutions for this:
Solution #1 ----------- count=1 until [ "$*" = "" ] do echo "Arg $count : $1 " shift let count+=1 done Solution #2 ----------- count=1 until [ "$*" = "" ] do echo "Arg $count : $1 " shift let count=count+1 done
senthil (28 Apr 2010, 04:31)
'''sh -x listarg abc def ''' Also Works , thanks
Bob Rankin (07 Apr 2010, 13:29)
That doesn't work either. As I mentioned above, you need to use the expr
command like this:
count=`expr $count + 1`
nolan (06 Apr 2010, 17:38)
minor tweak needed...
line 6 needs a space on each side of the "+". |
|
|
![]() |
|
| <Send This Link to a Friend> <Bookmark This Page> | ||