有人可以跟我解釋為什麼我的 while 迴圈似乎有內部作用域嗎?我在網路上看到了多種解釋,但它們都與管道有關。我的程式碼沒有。
代碼:
#!/bin/sh
while read line
do
echo "File contents: $line"
echo
if [ 1=1 ]; then
test1=bob
fi
echo "While scope:"
echo " test1: $test1"
done < test.txt
if [ 1=1 ]; then
test2=test2;
fi
echo;
echo "Script scope: "
echo " test1: $test1"
echo " test2: $test2"
輸出:
File contents: In the file
While scope:
test1: bob
Script scope:
test1:
test2: test2
答案1
在 Bourne shell 中,重定向複合指令(如迴圈while
)會在子 shell 中執行該複合指令。
在 Solaris 10 及更早版本1中,您不想使用它,/bin/sh
因為它是 Bourne shell。使用/usr/xpg4/bin/sh
or/usr/bin/ksh
來取得 POSIX sh
。
如果你因為某些原因必須使用/bin/sh
, 那麼要解決這個問題,而不是這樣做:
compound-command < file
你可以做:
exec 3<&0 < file
compound-command
exec <&3 3<&-
那是:
- 將 fd 0 複製到 fd 3 以將其儲存,然後將 fd 0 重定向到該檔案。
- 運行命令
- 從 fd 3 上儲存的副本恢復 fd 0。
1 .在 Solaris 11 及更高版本中,Oracle 最終(終於)製作了/bin/sh
POSIX shell,因此它現在的行為與sh
大多數其他 Unices 類似(它解釋sh
POSIX 指定的語言,儘管它支援對其進行擴展,因為它基於ksh88
(與其他Unices 一樣) ,sh
現在通常基於 ksh88、pdksh、bash、yash 或增強的 ash))