问题描述
if [ -n "${BASH-}" -o -n "${ZSH_VERSION-}" ] ; then
hash -r 2>/dev/null
fi
在哪里可以找到参考资料?谢谢.
Where can I find the reference on this? Thanks.
推荐答案
${...}
中的变量称为«参数扩展».
在在线手册或实际手册(第792行)中搜索该词.${var-}
形式与${var:-}
形式相似.区别仅在:-
扩展之前的一行(第810行)进行了解释:
Variables inside a ${...}
are called « Parameter Expansion ».
Search for that term in the online manual, or the actual manual (line 792).
The ${var-}
form is similar in form to ${var:-}
. The difference is explained just one line before the :-
expansion (line 810):
因此,此表单仅在未设置变量(和不为null)时进行测试,并将整个扩展${...}
替换为-
之后的值,在这种情况下为空.
Thus, this form is testing only when a variable is unset (and not null), and replaces the whole expansion ${...}
for the value after the -
, which in this case is null.
因此,${var-}
变为:
- 当var具有值(而不是null)时,var的值.
- 同样,当var为null时,var的值(冒号:丢失了!):
''
,因此:也为null. - 如果未设置var,则-之后的值(在本例中为null
''
).
- The value of var when var has a value (and not null).
- Also the value of var (the colon : is missing!) when var is null:
''
, thus: also null. - The value after the - (in this case, null
''
) if var is unset.
这就是真的:
- 当var未设置或为null时,扩展到
''
. - 扩展为var的值(当var具有值时).
因此,扩展名不会改变var的值,也不会扩展名,只是在shell设置了选项nounset
的情况下避免了可能的错误.
Therefore, the expansion changes nothing about the value of var, nor it's expansion, just avoids a possible error if the shell has the option nounset
set.
此代码将在同时使用$var
时停止:
This code will stop on both uses of $var
:
#!/bin/bash
set -u
unset var
echo "variable $var"
[[ $var ]] && echo "var set"
但是此代码将正确运行:
However this code will run without error:
#!/bin/bash
set -u
unset var
echo "variable ${var-}"
[[ ${var-} ]] && echo "var set"
这篇关于变量名后的'-'(破折号)在这里做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!