As I am a newbie in shell scripting, exec
command always confuses me and while exploring this topic with while
loop had triggered following 4 questions:
What is the difference between the below syntax 1 and 2
syntax 1:
while read LINE do : # manipulate file here done < file
syntax 2:
exec n<&0 < file while read LINE do : # manipulate file here done exec 0<&n n<&-
Kindly elaborate the operation of
exec n<&0 < file
lucidlyIs this
exec n<&0 < file
command equivalent toexec n<file
? (if not then what's the difference between two?)I had read some where that in Bourne shell and older versions of ksh, a problem with the
while
loop is that it is executed in a subshell. This means that any changes to the script environment,such as exporting variables and changing the current working directory, might not be present after thewhile
loop completes. As an example, consider the following script:#!/bin/sh if [ -f “$1” ] ; then i=0 while read LINE do i=`expr $i + 1` done < “$1” echo $i fi
This script tries to count the number of lines in the file specified to it as an argument.
On executing this script on the file
$ cat dirs.txt
/tmp
/usr/local
/opt/bin
/var
can produce the following incorrect result: 0
Although you are incrementing the value of $i using the command
i=expr $i + 1
when the while loop completes, the value of $i is not preserved.
In this case, you need to change a variable’s value inside the while
loop and then use that value outside the loop.
One way to solve this problem is to redirect STDIN prior to entering the loop and then restore STDIN after the loop completes.
The basic syntax is
exec n<&0 < file
while read LINE
do
: # manipulate file here
done
exec 0<&n n<&-
My question here is:
In Bourne shell and older versions of ksh,ALTHOUGH WHILE
LOOP IS EXECUTED IN SUBSHELL, how this exec
command here helps in retaining variable value even after while
loop completion i.e. how does here exec
command accomplishes the task change a variable’s value inside the while
loop and then use that value outside the loop.