Register
It is currently Thu Jul 31, 2014 5:27 am

Question about for loops


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Wed May 12, 2010 4:22 pm   

Joined: Wed May 12, 2010 3:52 pm
Posts: 1
Hello all I'm new here. I searched the web but couldn't find an answer to the following. Consider this very simple for loop.
Code:
for param in $1 $2; do
   echo "The parameters you gave are: "$param
done

Now if I run this script with two parameters it works perfectly. What I don't understand is when I run the script with only one parameter it still works. It will only execute the for loop once. Call me crazy but I thought for sure it would error out because $2 is unsigned. What is going on here? Is bash smart enough to drop $2 from the list because it doesn't exist? Or is this bad coding practice? I wan't my script to work on many different computers so I don't want any anomalous behavior.

Sorry if this is a silly question or if I am missing something obvious. I am new to bash and linux in general. Thx for the replies in advance!


Top
 Profile  
 PostPosted: Wed May 12, 2010 6:31 pm   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 533
Hi crazy,

add an -x to your shebang, and see how your loop works

bash doesn't drop $2, $2 is just considered by its value: '' (i.e. none)

if you want to treat all the parameters passed to your script, you could even omit the in $list part.


you could also do:
Code:
while [ -n "$1" ]
do echo "arg$((++n)) = $1"
   shift
done


good, bad coding practice? the real questions are:
- does it do the job?
- if it does, how could you optimize it?


Top
 Profile  
 PostPosted: Fri May 14, 2010 2:56 am   
Moderator
User avatar

Joined: Thu Oct 11, 2007 7:12 am
Posts: 229
Location: London - UK
bash interprets the line by putting in the variable values first so;

Code:
for param in $1 $2


where $1=one and $2 is blank the line looks like;

Code:
for param in one


this also demonstrates why quoting variables is important, consider where $1="one two" and $2="three four" the line would be interpreted as;

Code:
for param in one two three four


which would actually loop four times. Using quotes;

Code:
for param in "$1" "$2"


where $1 and $2 are as in the previous example, gets interpreted to

Code:
for param in "one two" "three four"


and would only be looped twice, with param="one two" and then "three four"


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 3 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP