Kai*_*Kai 33 variables syntax bash
使用这样的bash变量的含义是什么:
${Server?}
Run Code Online (Sandbox Code Playgroud)
pax*_*blo 42
它的工作方式几乎与(来自bash联机帮助页)相同:
${parameter:?word}
Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.
该特定变体检查以确保变量存在(既定义又不为空).如果是这样,它就会使用它.如果不是,则输出由word(或者如果没有word)指定的错误消息并终止脚本.
它与非冒号版本之间的实际差异可以在bash引用部分上方的联机帮助页中找到:
当不执行子字符串扩展时,使用下面记录的表单,
bash测试未设置或为null的参数.省略冒号只会导致对未设置的参数进行测试.
换句话说,上面的部分可以修改为read(基本上取出"null"位):
${parameter?word}
Display Error if Unset. If parameter is unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.
因此说明了不同之处:
pax> unset xyzzy ; export plugh=
pax> echo ${xyzzy:?no}
bash: xyzzy: no
pax> echo ${plugh:?no}
bash: plugh: no
pax> echo ${xyzzy?no}
bash: xyzzy: no
pax> echo ${plugh?no}
pax> _
Run Code Online (Sandbox Code Playgroud)
在那里,您可以看到,虽然unset 和 null变量都会导致错误:?,但只有未设置的错误?.
小智 14
这意味着如果未定义变量,脚本应该中止
例:
#!/bin/bash
echo We will see this
${Server?Oh no! server is undefined!}
echo Should not get here
Run Code Online (Sandbox Code Playgroud)
该脚本将打印出第一个echo,以及"Oh no!..."错误消息.
在这里查看bash的所有变量替换:http: //tldp.org/LDP/abs/html/parameter-substitution.html
按照man bash:
${parameter:?word}如果参数为 null 或未设置,则 word 的扩展(或者如果 word 不存在则显示一条消息)将写入标准错误,并且 shell(如果不是交互式的)将退出。否则,将替换参数的值。
因此,如果您省略word并且不传递$1给您的函数或 shell 脚本,那么它将退出并出现以下错误:
-bash: 1: parameter null or not set
Run Code Online (Sandbox Code Playgroud)
但是,您可以放置一个用户定义的错误,让您的调用者知道尚未设置所需的参数,例如:
local arg1="${1:?needs an argument}"
Run Code Online (Sandbox Code Playgroud)
$1仅当设置时,它才会继续运行脚本/函数。
:?如果给定参数为 null 或未设置,则导致(非交互式)shell 退出并显示错误消息。您正在查看的脚本省略了错误消息;通常,你会看到类似的东西
foo=${1:?Missing first argument}
Run Code Online (Sandbox Code Playgroud)
例如,
$ foo=${1:?Missing first argument}
bash: 1: Missing first argument
$ set firstarg
$ foo=${1:?Missing first argument}
$ echo $foo
firstarg
Run Code Online (Sandbox Code Playgroud)