Tutorials Point


  Unix for Beginners
  Unix Shell Programming
  Advanced Unix
  Unix Useful References
  Unix Useful Resources
  Selected Reading

© 2011 TutorialsPoint.COM


  Home     References     Discussion Forums     About TP  

Unix Shell - The for Loop


previous next AddThis Social Bookmark Button


The for loop operate on lists of items. It repeats a set of commands for every item in a list.

Syntax:

for var in word1 word2 ... wordN
do
   Statement(s) to be executed for every word.
done

Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words). Each time the for loop executes, the value of the variable var is set to the next word in the list of words, word1 to wordN.

Example:

Here is a simple example that uses for loop to span through the given list of numbers:

#!/bin/sh

for var in 0 1 2 3 4 5 6 7 8 9
do
   echo $var
done

This will produce following result:

0
1
2
3
4
5
6
7
8
9

Following is the example to display all the files starting with .bash and available in your home. I'm executing this script from my root:

#!/bin/sh

for FILE in $HOME/.bash*
do
   echo $FILE
done

This will produce following result:

/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc


previous next Printer Friendly



  

Advertisement

Online Image Processing

Indian Baby Names