先不正面回答问题。先谈一个脚本中可疑之处。
在对文件filename.txt的每一行进行相同或有规律的处理时,常用2种方法。
常用的第一种方法是(就是文件内容输入重定向的方法):
while read line
do
对$line的处理命令
done < filename.txt
常用的第二种方法是(cat加管道的方法):
cat filename.txt | while read line
do
对$line的处理命令
done
针对这2种方法,举例如下:
$ cat filename.txt
Jack
Mike
Rose
$ cat a1.sh
#!/bin/bash
while read line
do
echo "The name is $line"
done < filename.txt
$ cat a2.sh
#!/bin/bash
cat filename.txt | while read line
do
echo "My name is $line"
done
$ a1.sh (或者运行./a1.sh)
The name is Jack
The name is Mike
The name is Rose
$ a2.sh (或者运行./a2.sh)
My name is Jack
My name is Mike
My name is Rose
你在上面所提供的脚本中,cat加管道的方法(cat filename.txt | while...)、文件内容输入重定向的方法(...done < filename.txt )同时使用了,可能不算是问题,但几乎没有同时使用的。
下面言归正传。
下面的例子,一个输出flase, 一个输出true,看完例子就知道答案了:
$ cat filename.txt
Jack
Mike
Rose
$ cat b1.sh
#!/bin/bash
bl=false
cat filename.txt | while read line
do
bl=true
echo "x=$bl"
done
echo $bl
$ cat b2.sh
#!/bin/bash
bl=false
while read line
do
bl=true
echo "x=$bl"
done < filename.txt
echo $bl
$ b1.sh (或者运行./b1.sh)
x=true
x=true
x=true
false
$ b2.sh (或者运行./b2.sh)
x=true
x=true
x=true
true
供参考,谢谢!