我遇到过许多变量都是大写的shell脚本,我一直认为这是一个严重的误解。我的理解是,按照惯例(也许是很久以前的需要),环境变量都是大写的。

但是在像Bash这样的现代脚本环境中,我总是喜欢使用小写字母表示临时变量,而只对导出变量(即环境变量)使用大写字母。例如:

#!/usr/bin/env bash
year=$(date +%Y)
echo "It is $year."
export JAVA_HOME="$HOME/java"

这一直是我对事物的看法。是否有任何权威来源同意或不同意这种方法,或者这纯粹是一个风格问题?


当前回答

Bash, and most shell script interpreters, recognize global and local variables within functions (e.g typeset, declare, local) and should be used as appropriate. As previously commented, "Environment variable names used by the utilities in the Shell and Utilities volume of POSIX.1-2017 consist solely of uppercase letters, digits, and the underscore ( _ ) from the characters defined in Portable Character Set and do not begin with a digit. ... The name space of environment variable names containing lowercase letters is reserved for applications. Applications can define any environment variables with names from this name space without modifying the behavior of the standard utilities." (POSIX IEEE Std 1003.1-2008 section 8.1 )

其他回答

按照惯例,环境变量(PAGER, EDITOR,…)和内部shell变量(shell, BASH_VERSION,…)大写。所有其他变量名都应该小写。

记住变量名是区分大小写的;这种约定避免意外覆盖环境变量和内部变量。

按照这个约定,您可以放心,不需要知道UNIX工具或shell使用的每个环境变量,以避免覆盖它们。如果是变量,小写。如果要导出,请将其大写。

我倾向于对环境变量和全局变量都使用ALL_CAPS。当然,在Bash中没有真正的变量作用域,所以有相当一部分变量被用作全局变量(主要是设置和状态跟踪),而相对较少的“局部变量”(计数器、迭代器、部分构造的字符串和临时变量)。

我做你做的事。我怀疑是否有一个权威的来源,但这似乎是一个相当普遍的事实标准。

Bash, and most shell script interpreters, recognize global and local variables within functions (e.g typeset, declare, local) and should be used as appropriate. As previously commented, "Environment variable names used by the utilities in the Shell and Utilities volume of POSIX.1-2017 consist solely of uppercase letters, digits, and the underscore ( _ ) from the characters defined in Portable Character Set and do not begin with a digit. ... The name space of environment variable names containing lowercase letters is reserved for applications. Applications can define any environment variables with names from this name space without modifying the behavior of the standard utilities." (POSIX IEEE Std 1003.1-2008 section 8.1 )

这只是一个非常广泛的惯例,我怀疑是否有任何“权威”的来源。