The importance of the exec command when reading from a file

I found the following code snippet written as a shell script to read from 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 cannot understand the need to use the three mentioned exec commands. Can anyone develop it for me. Also is there a $ ifs reset variable after every read from the file?

+3
source share
2 answers

exec independently (without arguments) does not start a new process, but can be used to manage file descriptors in the current process.

What do these lines do:

  • temporarily save the current standard input (file descriptor 0) to file descriptor 3.
  • change the standard input to read from $FILE.
  • do the reading.
  • ( 3).

IFS reset read, "\n\b" while reset IFS=$BAKIFS ( ).


:

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.
+8

:

while read -r line
do
    ...
done < "$FILE"

, :

IFS=$'\n'

, Bash, .

0

Source: https://habr.com/ru/post/1784656/


All Articles