Bash   发布时间:2022-05-13  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了是否有更一致的方式来声明Bash变量和函数?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在决定如何在 Bash中声明变量或函数.

鉴于以下假设:

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

在全局变量的情况下,@R_221_10675@用:

> foo = bar – 函数内部和外部?
> declare -g foo = bar – 函数内部和外部?
> local -g foo = bar – 函数内部?

在局部变量的情况下,@R_221_10675@用:

>本地foo =吧
>声明foo = bar

在只读变量的情况下,@R_221_10675@用:

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

在函数的情况下,@R_221_10675@用:

> 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; }.
>最终的foo
> var foo = bar
> val foo = bar

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

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

大佬总结

以上是大佬教程为你收集整理的是否有更一致的方式来声明Bash变量和函数?全部内容,希望文章能够帮你解决是否有更一致的方式来声明Bash变量和函数?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: