我想让这个变量
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
}发布于 2016-11-02 05:51:14
在类似POSIX的shell中,-除非您使用local、typeset或declare等非标准构造,否则变量会隐式创建通过E210赋值在当前shell中具有E115作用域。<
因此,to="$HOME/root_install/grunt"将使变量$to在当前shell中的任何位置都可用-除非您在一个函数中,并且该变量被显式标记为本地变量。
andlrc's helpful answer演示了与子外壳相关的陷阱-子外壳是原始外壳的克隆的子进程-它们可以看到相同的状态,但不能修改原始外壳的环境。
发布于 2016-11-02 05:25:24
Bash shell使用dynamic scopes,这意味着所有被调用的函数、命令等都可以使用所有变量。
var=1
a() {
local var=2
b
}
b() {
echo "$var"
}
a # 2
b # 1
a # 2当使用local关键字时,一个变量将可用于定义该变量的函数,但也可用于从该函数调用的所有函数中。
当创建变量时没有使用local关键字,这一点同样适用。例外的是,它也可以在函数之外使用。
另一件需要注意的事情是,无论何时创建子subshell,变量都不能“离开”它,即当涉及到管道时。请考虑以下内容:
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?https://stackoverflow.com/questions/40368743
复制相似问题