开发者

importance of exec command while reading from file

开发者 https://www.devze.com 2023-02-03 19:07 出处:网络
I found following piece of code written as a shell script to read from a file line by line. BAKIFS=$IFS

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号