一、函数自动全局和局部修饰local
函数中的变量是全局变量,可被修改
to_delete]# a=3 to_delete]# function f() { echo $a;a=33; } [root@to_delete]# f 3 [root@to_delete]# echo $a 33
使用local修饰的是局部变量,在shell结束后无法访问
二、bash的变量属于动态作用域
#!/bin/bash # 全局变量x x=1 function f() { echo "f: $x"; x=2; } function g() { local x=3; f; echo "g: $x"; } g echo $x
记住bash是在哪里调用,变量就属于哪个作用域?
运行结果:
shellTest]# sh variableTest.sh f: 3 g: 2 1


