importance of exec command while reading from file
I found following piece of code written as a shell script to read from a file line by line.
BAKIFS=$IFS
IFS=$(echo -en "\n\b")
exec 3<&0
exec 0<"$FILE"
while read -r line
do
# use $line 开发者_Python百科variable to process line in processLine() function
processLine $line
done
exec 0<&3
# restore $IFS which was used to determine what the field separators are
IFS=$BAKIFS
I am unable to understand the need of three exec commands mentioned. Can someone elaborate it for me. Also is the $ifs variable reset after every single read from a file?
exec
on its own (with no arguments) will not start a new process but can be used to manipulate file handles in the current process.
What these lines are doing is:
- temporarily save the current standard input (file handle 0) into file handle 3.
- modify standard input to read from
$FILE
. - do the reading.
- set standard input back to the original value (from file handle 3).
IFS
is not reset after every read
, it stays as "\n\b"
for the duration of the while
loop and is reset to its original value with IFS=$BAKIFS
(saved earlier).
In detail:
BAKIFS=$IFS # save current input field separator
IFS=$(echo -en "\n\b") # and change it.
exec 3<&0 # save current stdin
exec 0<"$FILE" # and change it to read from file.
while read -r line ; do # read every line from stdin (currently file).
processLine $line # and process it.
done
exec 0<&3 # restore previous stdin.
IFS=$BAKIFS # and IFS.
The code shown is equivalent to:
while read -r line
do
...
done < "$FILE"
By the way, you can do this:
IFS=$'\n'
in shells such as Bash that support it.
精彩评论