Bash to Basics: The For Loop

February 14, 2010 by
Filed under: bash, HowTo, linux, Ubuntu 

Previously I've shown how to use the bash while loop in a bash script. Today I'm going to show how to use another type of do loop in bash: the for loop.

The for loop is a little different from the other looping structures in bash. The other loop structures work by evaluating whether an expression is true or false. The for loop works on lists of values. As long as there are items left in the list, the for loop will execute.

Here's a basic example.

#!/bin/bash

for i in {one,two,three,four,five,six,seven,eight,nine,ten}
do
	echo -en "$i "			# Print each value without a newline character
	sleep 0.5				# Slow things down with sleep
done						# End the loop
echo						# Move down to a new line

exit 0

Like I said, the for loop will work on any list of values. Try replacing the above for statement with each of the following.

for i in {1,2,3,4,5,6,7,8,9,10}
for i in {1..10}
for i in `seq 10`
for (( i=1; i<=10; i++ ))
for (( i=1; i<0; i++ ))


Do you know another way to control a for loop? Leave a comment.

Affiliate Link

Comments

2 Responses to “Bash to Basics: The For Loop”

  1. Story added...

    This story has been submitted to fsdaily.com! If you think this story should be read by the free software community, come vote it up and discuss it here:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>