我一直在争论如何在 Bash 中声明变量或函数的决定。
给定以下假设:
- Bash 是唯一可用的脚本语言。
- 命名约定无关紧要。
对于全局变量,我应该使用:
-
foo=bar
- 功能内部和外部? -
declare -g foo=bar
- 功能内部和外部? -
local -g foo=bar
- 函数内部?
对于局部变量,我应该使用:
-
local foo=bar
-
declare foo=bar
对于只读变量,我应该使用:
-
declare -r foo=bar
-
local -r foo=bar
-
readonly foo
- 在 [1.] 或 [2.] 之后,下一行没有-r
标志。
在函数的情况下,我应该使用:
-
foo() { echo bar; }
-
foo { echo bar; }
-
function foo() { echo bar; }
-
function foo { echo bar; }
忘记它,我在.bashrc
顶部附近以及每个Bash shell脚本文件附近定义了以下内容:
# Allow to define an alias.
#
shopt -s expand_aliases
# Defines a function given a name, empty parentheses and a block of commands enclosed in braces.
#
# @param name the name of the function.
# @param parentheses the empty parentheses. (optional)
# @param commands the block of commands enclosed in braces.
# @return 0 on success, n != 0 on failure.
#
alias def=function
# Defines a value, i.e. read-only variable, given options, a name and an assignment of the form =value.
#
# Viable options:
# * -i - defines an integer value.
# * -a - defines an array value with integers as keys.
# * -A - defines an array value with strings as keys.
#
# @param options the options. (optional)
# @param name the name of the value.
# @param assignment the equals sign followed by the value.
# @return 0 on success, n != 0 on failure.
#
alias val="declare -r"
# Defines a variable given options, a name and an assignment of the form =value.
#
# Viable options:
# * -i - defines an integer variable.
# * -a - defines an array variable with integers as keys.
# * -A - defines an array variable with strings as keys.
#
# @param options the options. (optional)
# @param name the name of the variable.
# @param assignment the equals sign followed by the value. (optional)
# @return 0 on success, n != 0 on failure.
#
alias var=declare
# Declares a function as final, i.e. read-only, given a name.
#
# @param name the name of the function.
# @return 0 on success, n != 0 on failure.
#
alias final="readonly -f"
上述定义允许我举例说:
-
def foo { echo bar; }
. -
final foo
-
var foo=bar
-
val foo=bar
如注释所示,您可以混合和匹配各种变量标志,例如全局 (-g) 变量 (var) 的 var -g foo=bar
或由整数 (-i) 值组成的只读 (val) 关联数组 (-A) 的 val -Ai foobar=([foo]=0 [bar]=1)
。
隐式变量范围也随此方法一起提供。此外,新引入的关键字def
,val
,var
和final
对于任何使用JavaScript,Java,Scala等语言进行编程的软件工程师来说都应该很熟悉。