Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importance of exec command while reading from file

Tags:

shell

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 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?

like image 416
ayush Avatar asked Jan 21 '23 18:01

ayush


1 Answers

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.
like image 128
paxdiablo Avatar answered Jan 23 '23 08:01

paxdiablo