[英]Is there file scope in bash programming?
我想讓這個變量
local to="$HOME/root_install/grunt"
可用於整個文件
makeGrunt(){
# set paths
local to="$HOME/root_install/grunt"
cd $to
sudo npm install -g grunt-init
sudo git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
sudo grunt-init gruntfile
}
在類似POSIX的外殼程序中 -除非您使用非標准結構(例如local
, typeset
或declare
- 通過賦值 隱式創建的變量在外殼程序中具有全局作用域。
因此, to="$HOME/root_install/grunt"
將使變量$to
在當前shell中的任何位置可用-除非您位於函數內部並且該變量被顯式標記為local 。
andlrc的有用答案說明了與子外殼程序相關的陷阱 -子外殼程序是原始外殼程序的克隆的子進程-它們看到相同的狀態,但不能修改原始外殼程序的環境 。
Bash shell使用動態范圍 ,這意味着所有變量可用於所有調用的函數,命令等。請考慮以下事項:
var=1
a() {
local var=2
b
}
b() {
echo "$var"
}
a # 2
b # 1
a # 2
當使用local
關鍵字時,變量將在該函數定義的位置可用,也可以在該函數調用的所有函數中使用。
創建不帶local
關鍵字的變量時,也是如此。 除此之外,它也將在功能之外可用。
還有一點要注意的是,無論何時創建子外殼,變量都將無法“離開”它,即當涉及管道時。 考慮一下:
sum=0
seq 3 | while read -r num; do
sum=$((sum + num))
echo "$sum" # will print 1, 3 and 6
done
echo "$sum" # 0 huh? 1 + 2 + 3 = 0?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.