我们已经讨论了一些对调试脚本很有用处的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
See the Bash Info pages, section xtrace
option, for instance, is equal to specifying set -x
.
Shell options can either be set different from the default upon calling the shell, or be set during shell operation. They may also be included in the shell resource configuration files.
The following command executes a script in POSIX-compatible mode:
willy:~/scripts>
bash--posix
script.sh
需要临时改变当前的环境,或者需要在脚本中使用,我们不如使用 set。使用 - (dash)来开启一个选项 + 来关闭:
willy:~/test>
set-o
noclobber
willy:~/test>
touchtest
willy:~/test>
date >test
bash: test: cannot overwrite existing filewilly:~/test>
set+o
noclobber
willy:~/test>
date >test
以上的例子证明了 noclobber
选项, which prevents existing files from being overwritten by redirection operations. The same goes for one-character options,
for instance -u
, which will treat unset variables as an error when set, and exits a non-interactive shell upon
encountering such errors:
willy:~>
echo$VAR
willy:~>
set-u
willy:~>
echo$VAR
bash: VAR: unbound variable
This option is also useful for detecting incorrect content assignment to variables: the same error will also occur, for instance, when assigning a character string to a variable that was declared explicitly as one holding only integer values.
One last example follows, demonstrating the noglob
option, which prevents special characters from being expanded:
willy:~/testdir>
set-o
noglob
willy:~/testdir>
touch*
willy:~/testdir>
ls-l
*
-rw-rw-r-- 1 willy willy 0 Feb 27 13:37 *