Bash编程:参数扩展、字符串操作与算术运算全解析
1. 参数扩展基础
参数扩展是Bash中一项强大的功能,它允许我们对变量进行各种操作。以下是一些常见的参数扩展形式及其示例:
- ${parameter:?"error message"}
:如果参数未设置或为空,则显示错误信息。
[me@linuxbox ~]$ foo=bar
[me@linuxbox ~]$ echo ${foo:?"parameter is empty"}
bar
-
${parameter:+word}
:如果参数已设置且不为空,则返回word
;否则返回空。
[me@linuxbox ~]$ foo=
[me@linuxbox ~]$ echo ${foo:+"substitute value if set"}
[me@linuxbox ~]$ foo=bar
[me@linuxbox ~]$ echo ${foo:+"substitute value if set"}
substitute value if set
-
${!prefix*}
和${!prefix@}
:返回以prefix
开头的所有现有变量的名称。