我遇到过许多变量都是大写的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 )
始终遵循的命名约定总是有帮助的。下面是一些有用的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期-环境变量