是否有更一致的方式来声明Bash变量和函数?

时间:2012-11-12 23:42:50

标签: bash shell

我一直在决定如何在Bash中声明一个变量或函数。

考虑以下假设:

  1. Bash是唯一可用的脚本语言。
  2. 命名约定无关紧要。
  3. 对于全局变量,我应该使用:

    1. foo=bar - 功能内外?
    2. declare -g foo=bar - 功能内外?
    3. local -g foo=bar - 功能内部?
    4. 对于 local 变量,我应该使用:

      1. local foo=bar
      2. declare foo=bar
      3. 对于只读变量,我应该使用:

        1. declare -r foo=bar
        2. local -r foo=bar
        3. readonly foo - 在下一行没有-r标记的[1.]或[2.]之后。
        4. 如果我应该使用函数:

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

1 个答案:

答案 0 :(得分: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
  5. 如注释所示,您可以混合和匹配各种变量标志,例如var -g foo=bar表示全局(-g)变量(var)或val -Ai foobar=([foo]=0 [bar]=1)表示只读(val),关联数组(-A)由整数(-i)值组成。

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