我一直在为如何在 Bash 中声明变量或函数的决定而斗争。
鉴于以下假设:
- Bash 是唯一可用的脚本语言。
- 命名约定无关紧要。
对于全局变量,我应该使用:
foo=bar
- 函数内部和外部?declare -g foo=bar
- 函数内部和外部?local -g foo=bar
- 函数内部?
对于本地变量,我应该使用:
本地 foo=bar
声明 foo=bar
对于只读变量,我应该使用:
声明 -r foo=bar
local -r foo=bar
readonly foo
- 在 [1.] 或 [2.] 之后的下一行没有-r
标志。
对于函数,我应该使用:
foo() { 回显栏; }
foo { echo 栏; }
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;
。最终 foo
var foo=bar
val foo=bar
如注释所示,您可以混合和匹配各种变量标志,例如 var -g foo=bar
用于全局 (-g) 变量 (var) 或 val -Ai foobar =([foo]=0 [bar]=1)
用于只读 (val)、由整数 (-i) 值组成的关联数组 (-A)。
这种方法也带有隐式变量范围。此外,新引入的关键字 def
、val
、var
和 final
对任何在JavaScript、Java、Scala 等语言。
关于bash - 是否有更一致的方式来声明 Bash 变量和函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13353474/