bash 变量参数扩展中的问号(如 ${var?})的含义是什么?
像这样使用的 bash 变量的含义是什么:
${Server?}
What is the meaning of a bash variable used like this:
${Server?}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它的工作原理几乎与(来自
bash
联机帮助页)相同:该特定变体检查以确保变量存在(已定义且不为空)。如果是这样,它就会使用它。如果没有,它会输出由
word
指定的错误消息(如果没有word
,则输出合适的错误消息)并终止脚本。其与非冒号版本之间的实际区别可以在引用部分上方的
bash
联机帮助页中找到:换句话说,上面的部分可以修改为读取(基本上去掉“空”位):
差异如下所示:
在那里,您可以看到,虽然 unset 和 null 变量都会导致
:?,只有未设置的一个错误为
?
。It works almost the same as (from the
bash
manpage):That particular variant checks to ensure the variable exists (is both defined and not null). If so, it uses it. If not, it outputs the error message specified by
word
(or a suitable one if there is noword
) and terminates the script.The actual difference between that and the non-colon version can be found in the
bash
manpage above the section quoted:In other words, the section above can be modified to read (basically taking out the "null" bits):
The difference is illustrated thus:
There, you can see that while both unset and null variable result in an error with
:?
, only the unset one errors with?
.这意味着如果未定义变量,脚本应中止
示例:
此脚本将打印出第一个回显,以及“哦不!...”错误消息。
在这里查看 bash 的所有变量替换:
https://www.gnu.org/software/ bash/manual/html_node/Shell-Parameter-Expansion.html
It means that the script should abort if the variable isn't defined
Example:
This script will print out the first echo, and the "Oh no! ..." error message.
See all the variable substitutions for bash here:
https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
根据
man bash
:${parameter:?word}
因此,如果您省略
word
并且不将$1
传递给您的函数或 shell 脚本,那么它将退出并显示此错误:但是您可以放置一个用户定义的错误来让您的调用者知道尚未设置必需的参数,例如:
仅当设置了
$1
时,它才会继续运行脚本/函数。As per
man bash
:${parameter:?word}
So if you omit
word
and don't pass$1
to your function or shell script then it will exit with this error:However you can place a user-defined error to let your caller know that a required argument has not been set e.g.:
It will continue running script/function only if
$1
is set.如果给定参数为 null 或未设置,
:?
会导致(非交互式)shell 退出并显示错误消息。您正在查看的脚本省略了错误消息;通常,您会看到类似的内容例如,
:?
causes the (non-interactive) shell to exit with an error message if given parameter is null or unset. The script you are looking at is omitting the error message; usually, you'd see something likeFor example,