5

我一直在为如何在 Bash 中声明变量或函数的决定而斗争。

鉴于以下假设:

  1. Bash 是唯一可用的脚本语言。
  2. 命名约定无关紧要。

全局变量的情况下,我应该使用:

  1. foo=bar- 功能的内部和外部?
  2. declare -g foo=bar- 功能的内部和外部?
  3. local -g foo=bar- 函数内部?

局部变量的情况下,我应该使用:

  1. local foo=bar
  2. declare foo=bar

只读变量的情况下,我应该使用:

  1. declare -r foo=bar
  2. local -r foo=bar
  3. readonly foo- 在 [1.] 或 [2.]-r之后,下一行没有标志。

在函数的情况下,我应该使用:

  1. foo() { echo bar; }
  2. foo { echo bar; }
  3. function foo() { echo bar; }
  4. function foo { echo bar; }
4

1 回答 1

2

为了忘记它,我在我.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"

上面的定义让我可以说例如:

  1. def foo { echo bar; }.
  2. final foo
  3. var foo=bar
  4. val foo=bar

如注释所示,您可以混合和匹配各种变量标志,例如var -g foo=bar全局(-g)变量(var)或val -Ai foobar=([foo]=0 [bar]=1)只读(val),由整数(-i)值组成的关联数组(-A) .

这种方法也带有隐式变量范围。此外,任何使用 JavaScript、Java、Scala 等语言编程的软件工程师都应该熟悉新引入的关键字def、和。valvarfinal

于 2012-11-12T23:42:49.920 回答