3.6. 更多 Bash 选项

3.6.1. 显示选项

我们已经讨论过一些 Bash 选项,它们对于调试脚本很有用。在本节中,我们将更深入地了解 Bash 选项。

使用-o选项来set 显示所有 shell 选项

willy:~> set -o
allexport		off
braceexpand		on
emacs			on
errexit			off
hashall			on
histexpand		on
history			on
ignoreeof		off
interactive-comments	on
keyword			off
monitor			on
noclobber		off
noexec			off
noglob			off
nolog			off
notify			off
nounset			off
onecmd			off
physical		off
posix			off
privileged		off
verbose			off
vi			off
xtrace			off

请参阅 Bash Info 页面,Shell Built-in Commands->The Set Built-in 章节,其中描述了每个选项。许多选项都有单字符简写形式:例如xtrace选项,例如,等同于指定 set -x

3.6.2. 更改选项

Shell 选项可以在调用 shell 时设置为不同于默认值,也可以在 shell 运行期间设置。它们也可以包含在 shell 资源配置文件中。

以下命令以 POSIX 兼容模式执行脚本

willy:~/scripts> bash --posix script.sh

为了临时更改当前环境,或者在脚本中使用,我们更愿意使用 set 命令。使用 - (短划线) 来启用选项,+ 来禁用

willy:~/test> set -o noclobber

willy:~/test> touch test

willy:~/test> date > test
bash: test: cannot overwrite existing file

willy:~/test> set +o noclobber

willy:~/test> date > test

上面的例子演示了noclobber选项,它可以防止现有文件被重定向操作覆盖。单字符选项也是如此,例如-u,当设置后,它会将未设置的变量视为错误,并在非交互式 shell 中遇到此类错误时退出

willy:~> echo $VAR


willy:~> set -u

willy:~> echo $VAR
bash: VAR: unbound variable

此选项也适用于检测变量的不正确内容赋值:例如,当将字符串赋值给显式声明为仅保存整数值的变量时,也会发生相同的错误。

最后一个例子如下,演示了noglob选项,它可以防止特殊字符被扩展

willy:~/testdir> set -o noglob

willy:~/testdir> touch *

willy:~/testdir> ls -l *
-rw-rw-r--    1 willy    willy		0 Feb 27 13:37 *