声明为 局部 的变量是指仅在其出现的代码块内可见的变量。它具有局部的作用域。在函数中,局部变量 仅在该函数块内有意义。[1]
示例 24-12. 局部变量可见性
#!/bin/bash
# ex62.sh: Global and local variables inside a function.
func ()
{
local loc_var=23 # Declared as local variable.
echo # Uses the 'local' builtin.
echo "\"loc_var\" in function = $loc_var"
global_var=999 # Not declared as local.
# Therefore, defaults to global.
echo "\"global_var\" in function = $global_var"
}
func
# Now, to see if local variable "loc_var" exists outside the function.
echo
echo "\"loc_var\" outside function = $loc_var"
# $loc_var outside function =
# No, $loc_var not visible globally.
echo "\"global_var\" outside function = $global_var"
# $global_var outside function = 999
# $global_var is visible globally.
echo
exit 0
# In contrast to C, a Bash variable declared inside a function
#+ is local ONLY if declared as such. |
![]() | 在函数被调用之前,所有在函数内声明的变量在函数体外部都是不可见的,不仅仅是那些显式声明为 局部 的变量。
|
![]() | 正如 Evgeniy Ivanov 指出的那样,当在单个命令中声明和设置局部变量时,操作顺序显然是首先设置变量,然后才将其限制为局部作用域。这反映在返回值中。
|
递归 是一种有趣且有时有用的 自引用 形式。Herbert Mayer 将其定义为 ". . . 通过使用同一算法的更简单版本来表达算法 . . ." 考虑一个根据自身定义的定义,[2] 一个隐含在其自身表达式中的表达式,[3] 一条蛇吞噬自己的尾巴,[4] 或者... 一个调用自身的函数。[5] 示例 24-13. 简单递归函数演示
示例 24-14. 另一个简单演示
|
局部变量是编写递归代码的有用工具,但这种做法通常涉及大量的计算开销,并且绝对不建议在 shell 脚本中使用。[6]
示例 24-15. 递归,使用局部变量
#!/bin/bash
# factorial
# ---------
# Does bash permit recursion?
# Well, yes, but...
# It's so slow that you gotta have rocks in your head to try it.
MAX_ARG=5
E_WRONG_ARGS=85
E_RANGE_ERR=86
if [ -z "$1" ]
then
echo "Usage: `basename $0` number"
exit $E_WRONG_ARGS
fi
if [ "$1" -gt $MAX_ARG ]
then
echo "Out of range ($MAX_ARG is maximum)."
# Let's get real now.
# If you want greater range than this,
#+ rewrite it in a Real Programming Language.
exit $E_RANGE_ERR
fi
fact ()
{
local number=$1
# Variable "number" must be declared as local,
#+ otherwise this doesn't work.
if [ "$number" -eq 0 ]
then
factorial=1 # Factorial of 0 = 1.
else
let "decrnum = number - 1"
fact $decrnum # Recursive function call (the function calls itself).
let "factorial = $number * $?"
fi
return $factorial
}
fact $1
echo "Factorial of $1 is $?."
exit 0 |
另请参阅 示例 A-15,了解脚本中递归的示例。请注意,递归是资源密集型的,执行缓慢,因此通常不适用于脚本。
| [1] | 但是,正如 Thomas Braunberger 指出的那样,在函数中声明的局部变量对于父函数调用的函数也是可见的。
这在 Bash 手册中有所记录 “Local 只能在函数内部使用;它使变量名具有可见的作用域,该作用域仅限于该函数及其子函数。” [强调添加] 《ABS 指南》的作者认为此行为是一个错误。 | |
| [2] | 也称为冗余。 | |
| [3] | 也称为同义反复。 | |
| [4] | 也称为隐喻。 | |
| [5] | 也称为递归函数。 | |
| [6] | 过多的递归层级可能会导致脚本因段错误而崩溃。
|