Options are settings that change shell and/or script behavior.
The set command enables options within a script. At the point in the script where you want the options to take effect, use set -o option-name or, in short form, set -option-abbrev. These two forms are equivalent.
1 #!/bin/bash 2 3 set -o verbose 4 # Echoes all commands before executing. 5 |
1 #!/bin/bash 2 3 set -v 4 # Exact same effect as above. 5 |
To disable an option within a script, use set +o option-name or set +option-abbrev. |
1 #!/bin/bash 2 3 set -o verbose 4 # Command echoing on. 5 command 6 ... 7 command 8 9 set +o verbose 10 # Command echoing off. 11 command 12 # Not echoed. 13 14 15 set -v 16 # Command echoing on. 17 command 18 ... 19 command 20 21 set +v 22 # Command echoing off. 23 command 24 25 exit 0 26 |
An alternate method of enabling options in a script is to specify them immediately following the #! script header.
1 #!/bin/bash -x 2 # 3 # Body of script follows. 4 |
It is also possible to enable script options from the command line. Some options that will not work with set are available this way. Among these are -i, force script to run interactive.
bash -v script-name
bash -o verbose script-name
The following is a listing of some useful options. They may be specified in either abbreviated form or by complete name.
Table 31-1. Bash options
Abbreviation | Name | Effect |
---|---|---|
-C | noclobber | Prevent overwriting of files by redirection (may be overridden by >|) |
-D | (none) | List double-quoted strings prefixed by $, but do not execute commands in script |
-a | allexport | Export all defined variables |
-b | notify | Notify when jobs running in background terminate (not of much use in a script) |
-c ... | (none) | Read commands from ... |
-f | noglob | Filename expansion (globbing) disabled |
-i | interactive | Script runs in interactive mode |
-p | privileged | Script runs as "suid" (caution!) |
-r | restricted | Script runs in restricted mode (see Chapter 21). |
-u | nounset | Attempt to use undefined variable outputs error message, and forces an exit |
-v | verbose | Print each command to stdout before executing it |
-x | xtrace | Similar to -v, but expands commands |
-e | errexit | Abort script at first error (when a command exits with non-zero status) |
-n | noexec | Read commands in script, but do not execute them (syntax check) |
-s | stdin | Read commands from stdin |
-t | (none) | Exit after first command |
- | (none) | End of options flag. All other arguments are positional parameters. |
-- | (none) | Unset positional parameters. If arguments given (-- arg1 arg2), positional parameters set to arguments. |