正确的 Bash 和 shell 脚本变量大小写 [英] Correct Bash and shell script variable capitalization

查看:64
本文介绍了正确的 Bash 和 shell 脚本变量大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到过许多变量全部大写的 shell 脚本,我一直认为对此存在严重的误解.我的理解是,按照惯例(也许很久以前是必要的),环境变量都是大写的.

I run across many shell scripts with variables in all caps, and I've always thought that there is a severe misunderstanding with that. My understanding is that, by convention (and perhaps by necessity long ago), environment variables are in all-caps.

但是在像 Bash 这样的现代脚本环境中,我总是倾向于将小写名称用于临时变量,而大写名称​​仅用于导出(即环境)变量.例如:

But in modern scripting environments like Bash, I have always preferred the convention of lower-case names for temporary variables, and upper-case ones only for exported (i.e. environment) variables. For example:

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

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

That has always been my take on things. Are there any authoritative sources which either agree or disagree with this approach, or is it purely a matter of style?

推荐答案

按照惯例,环境变量(PAGEREDITOR、...)和内部 shell 变量(SHELL, BASH_VERSION, ...) 是大写的.所有其他变量名都应该小写.

By convention, environment variables (PAGER, EDITOR, ...) and internal shell variables (SHELL, BASH_VERSION, ...) are capitalized. All other variable names should be lower case.

记住变量名区分大小写;此约定可避免意外覆盖环境和内部变量.

Remember that variable names are case-sensitive; this convention avoids accidentally overriding environmental and internal variables.

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

Keeping to this convention, you can rest assured that you don't need to know every environment variable used by UNIX tools or shells in order to avoid overwriting them. If it's your variable, lowercase it. If you export it, uppercase it.

这篇关于正确的 Bash 和 shell 脚本变量大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆