按优先级顺序:保持跟你所发现的一致;引用你的变量;推荐用 ${var} 而不是 $var ,详细解释如下。 这些仅仅是指南,因为作为强制规定似乎饱受争议。
以下按照优先顺序列出。
与现存代码中你所发现的保持一致。
引用变量参阅下面一节,引用。
除非绝对必要或者为了避免深深的困惑,否则不要用大括号将单个字符的 shell 特殊变量或定位变量括起来。推荐将其他所有变量用大括号括起来。
# Section of recommended cases.
# Preferred style for 'special' variables:
echo "Positional: $1" "$5" "$3"
echo "Specials: !=$!, -=$-, _=$_. ?=$?, #=$# *=$* @=$@ \$=$$ ..."
# Braces necessary:
echo "many parameters: ${10}"
# Braces avoiding confusion:
# Output is "a0b0c0"
set -- a b c
echo "${1}0${2}0${3}0"
# Preferred style for other variables:
echo "PATH=${PATH}, PWD=${PWD}, mine=${some_var}"
while read f; do
echo "file=${f}"
done < <(ls -l /tmp)
# Section of discouraged cases
# Unquoted vars, unbraced vars, brace-quoted single letter
# shell specials.
echo a=$avar "b=$bvar" "PID=${$}" "${1}"
# Confusing use: this is expanded as "${1}0${2}0${3}0",
# not "${10}${20}${30}
set -- a b c
echo "$10$20$30"