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

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

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

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


当前回答

实际上,“环境变量”这个术语似乎是最近才出现的。Kernighan和Pike在他们1984年出版的经典著作《UNIX编程环境》中,只提到了“shell变量”——在索引中甚至没有“环境”的条目!

其他回答

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 )

如果要将shell变量导出到环境中,值得考虑的是POSIX (Issue 7, 2018 edition)环境变量定义指定:

Shell和utilities中实用程序使用的环境变量名 卷POSIX.1-2017仅由大写字母,数字和 下划线(_)从可移植字符集中定义的字符 不要以数字开头。

...

包含小写字母的环境变量名称空间为 预留给应用程序。应用程序可以定义任何环境变量 类的行为 标准的公用事业公司。

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

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

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

实际上,“环境变量”这个术语似乎是最近才出现的。Kernighan和Pike在他们1984年出版的经典著作《UNIX编程环境》中,只提到了“shell变量”——在索引中甚至没有“环境”的条目!

始终遵循的命名约定总是有帮助的。下面是一些有用的shell变量命名技巧:

Use all caps and underscores for exported variables and constants, especially when they are shared across multiple scripts or processes. Use a common prefix whenever applicable so that related variables stand out and won't clash with Bash internal variables which are all upper case. Examples: Exported variables with a common prefix: JOB_HOME JOB_LOG JOB_TEMP JOB_RUN_CONTROL Constants: LOG_DEBUG LOG_INFO LOG_ERROR STATUS_OK STATUS_ERROR STATUS_WARNING Use "snake case" (all lowercase and underscores) for all variables that are scoped to a single script or a block. Examples: input_file first_value max_amount num_errors Use mixed case when local variable has some relationship with an environment variable, like: old_IFS old_HOME Use a leading underscore for "private" variables and functions. This is especially relevant if you ever write a shell library where functions within a library file or across files need to share variables, without ever clashing with anything that might be similarly named in the main code. Examples: _debug _debug_level _current_log_file Avoid camel case. This will minimize the bugs caused by case typos. Remember, shell variables are case sensitive. Examples: inputArray thisLooksBAD, numRecordsProcessed, veryInconsistent_style


参见:

开放组基础规范第7期-环境变量