Ann*_*sum 6 shell shell-script
“冒号”和“美元问号”可以组合起来检查脚本是否sh有参数并将其直接分配给感兴趣的变量:
cmd=${1:? "Usage: $0 {build|upload|log}"}
Run Code Online (Sandbox Code Playgroud)
有人可以一步步解释它是如何工作的,以及我在哪里可以找到其实现的详细信息吗?例如,我希望能够调用函数而不是打印到stderr.
help() {
echo $"Usage: $0 {build|upload|log}"
exit 1
}
cmd=${1:? help}
Run Code Online (Sandbox Code Playgroud)
为什么这是不可能的?
这在变量扩展中有所介绍:
${parameter:?word}
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.
Run Code Online (Sandbox Code Playgroud)
因此,如果没有argument执行脚本,则该变量cmd将help被写入标准输出并返回到 shell。
然而,它只是读入并没有执行。如果你用反引号括起来,那么它将被执行并运行Usage函数:
help() {
echo "Usage: $0 {build|upload|log}"
}
cmd=${1:? `help`}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这仍然会出现 stderr,正如变量扩展的设计目的。
您也可以执行以下操作:
cmd=${1:-help}
$cmd
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5049 次 |
| 最近记录: |