本文介绍了变量名后的'-'(破折号)在这里做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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-}变为:

  1. 当var具有值(而不是null)时,var的值.
  2. 同样,当var为null时,var的值(冒号:丢失了!):'',因此:也为null.
  3. 如果未设置var,则-之后的值(在本例中为null '').
  1. The value of var when var has a value (and not null).
  2. Also the value of var (the colon : is missing!) when var is null:'', thus: also null.
  3. The value after the - (in this case, null '') if var is unset.

这就是真的:

  1. 当var未设置或为null时,扩展到''.
  2. 扩展为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"

这篇关于变量名后的'-'(破折号)在这里做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!