Distributed Networks Distributed Networks

Unix Shell Programming   «Prev  Next»
Lesson 5 Using embedded execution in a for loop
Objective Embed a command within a for loop.
Embedded execution is commonly used in conjunction with the for loop to cycle through the output of a command or to cycle through the lines of a file. Place the embedded command in place of the list of values used by the for loop. Assume you have a file called firstname:
$ cat firstname
To cycle through the contents of this file, use an embedded cat command in a for loop:
$ for name in `cat firstname`
> do
>  echo $name is your name
> done
Harry is your name
Fred is your name
Sally is your name
The shell will cat out the contents of the firstname file and use this as the set of values copied to the name variable.
Carriage returns
When embedded execution output is a list of values used in a for loop, the shell divides this output by spaces and by carriage returns. Sometimes, you’ll want to divide the output by carriage return only. By changing the value of the environment variable IFS, you can change this behavior of the for loop. The for loop uses the value of IFS to divide the command output that it uses as values. IFS defaults to spaces, tabs, and carriage returns. Change this value to carriage returns only by setting IFS to the value control-M. This represents a carriage return.
Let's look at a Insert Carriage Return illustrating this. Here's an example where each line is used as one value:
$ IFS=^M
$ for name in `cat fullnames`
> do
>  echo $name is your name
> done
Harry Smith
Fred Brown
Sally Green
Doris Jones
Martha Jackson is your name