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

标签 bash shell

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

鉴于以下假设:

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

对于全局变量,我应该使用:

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

对于本地变量,我应该使用:

  1. 本地 foo=bar
  2. 声明 foo=bar

对于只读变量,我应该使用:

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

对于函数,我应该使用:

  1. foo() { 回显栏; }
  2. foo { echo 栏; }
  3. function foo() { echo bar; }
  4. 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"

上面的定义让我可以这样说:

  1. def foo { echo bar;
  2. 最终 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)。

这种方法也带有隐式变量范围。此外,新引入的关键字 defvalvarfinal 对任何在JavaScript、Java、Scala 等语言。

关于bash - 是否有更一致的方式来声明 Bash 变量和函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13353474/

相关文章:

bash - 获取文件数量并遍历它们

bash - Brew 显示 elasticsearch 服务器正在运行,但对 elasticsearch 服务器的请求一直失败

shell - 通过 telnet 获取 imap body 信息

linux - 是否可以使用 shell 清理 Linux VPS?

linux - Xubuntu LTS 16.0.4 无法识别 bash 脚本

python - 根据某种模式和 block 内的信息分割文件

Node.js Unix 套接字不回显

linux - 用从另一个文件复制的内容替换文件中的字符串

linux - 如何在 red hat Linux shell 脚本中获取指定用户的桌面文件夹

shell - 在 unix shell 脚本中将多个文件合并为单个文件