wqfhenanxc@ubuntu:~$ cat test.sh
#!/bin/bash
Lines=0
cat $0 | while read line
do
((Lines++))
done
echo "Number of lines read is: $Lines"
exit 0
wqfhenanxc@ubuntu:~$ ./test.sh
Number of lines read is: 0
wqfhenanxc@ubuntu:~$ cat test.sh
#!/bin/bash
Lines=0
while read line
do
((Lines++))
done <$0
echo "Number of lines read is: $Lines"
exit 0
wqfhenanxc@ubuntu:~$ ./test.sh
Number of lines read is: 8
上面兩個腳本一個使用了管道來讀文件,一個使用了重定向來讀。
結果爲什麼不一樣呢?
請大家從腳本執行的本質上來給一下解答。
背景知識:
1.當我在命令行中輸入./test.sh時,當前shell創建子shell。
子shell讀取test.sh中的命令,對於每一行命令,都先調用fork再調用exec。
#!/bin/bash
Lines=0
cat $0 | while read line
do
((Lines++))
done
echo "Number of lines read is: $Lines"
exit 0
wqfhenanxc@ubuntu:~$ ./test.sh
Number of lines read is: 0
wqfhenanxc@ubuntu:~$ cat test.sh
#!/bin/bash
Lines=0
while read line
do
((Lines++))
done <$0
echo "Number of lines read is: $Lines"
exit 0
wqfhenanxc@ubuntu:~$ ./test.sh
Number of lines read is: 8
上面兩個腳本一個使用了管道來讀文件,一個使用了重定向來讀。
結果爲什麼不一樣呢?
請大家從腳本執行的本質上來給一下解答。
背景知識:
1.當我在命令行中輸入./test.sh時,當前shell創建子shell。
子shell讀取test.sh中的命令,對於每一行命令,都先調用fork再調用exec。
2.對於管道,子shell先創建管道描述符,然後再fork出管道兩邊的兩個子進程,讓後將一個子進程的輸出重定向給另一個子進程的輸入。