2011-01-11 92 views
3

我发现下面一段代码被写为shell脚本以逐行读取文件。从文件中读取时执行exec命令的重要性

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 

我无法理解需要提到的三个exec命令。有人能为我详细说明吗?在每次从文件读取之后,$ ifs变量是否重置?

回答

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

非常感谢pax ....假设我在后台服务器上运行此脚本。然后在while循环的持续时间期间标准输入将设置为3.这是否意味着我不能使用标准输入在这段时间内阅读任何其他程序?任何想法,以消除这种依赖? – ayush 2011-01-11 06:28:42

0

显示的代码等同于:在外壳如

IFS=$'\n' 

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

顺便说一句,你可以这样做作为支持它的Bash。