从文件读取时exec命令的重要性

ayu*_*ush 3 shell

我发现下面的一段代码被编写为shell脚本,可以逐行读取文件.

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
Run Code Online (Sandbox Code Playgroud)

我无法理解提到的三个exec命令的必要性.有人可以为我详细说明.每次从文件中读取后,$ ifs变量也会重置吗?

pax*_*blo 8

exec 单独(没有参数)将不会启动新进程,但可以用于操作当前进程中的文件句柄.

这些行正在做的是:

  • 暂时将当前标准输入(文件句柄0)保存到文件句柄3中.
  • 修改要读取的标准输入$FILE.
  • 读书.
  • 将标准输入设置回原始值(来自文件句柄3).

IFS每次都没有重置read,它"\n\b"while循环的持续时间内保持不变,并通过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.
Run Code Online (Sandbox Code Playgroud)