Shellopts in Bash | linux

SHELLOPTS is similar to BASHOPTS; it is a list of -o options set. So if you set -o vi, then vi will appear in the list of options, and the shell will work in its vi. Like BASHOPTS, SHELLOPTS is read-only. You can use one of two different methods to set most of these; some only work with one method or the other. Here, you can use either syntax to turn the errexit feature on (-e, or -o errexit), and then off again (+e or +o errexit):



$ set -e



$ set +o errexit




Again, these are all documented in the set builtin section of the bash man page, but here are a few of the more commonly used options. A lot of these shell options also work in other shells:

➤➤ -e / -o errexit — Exit if any command returns a non-zero exit status code. This can be useful

if you are sure that every single command in a script must succeed, and that exiting otherwise is the safest thing to do.

➤➤ -f / -o noglob — Disables pathname expansion.

➤➤ -m / -o monitor — If set (which it is by default), when a background command completes, you will get a line the next time bash displays a new prompt:

$ ls /tmp & [1] 2922 keyring-UDudcH orbit-steve

OSL_PIPE_1000_SingleOfficeIPC_54f1d8557767a73f9bc36a8c3028b0 pulse-Mm0m5cufbNQY

ssh-EwfFww1963 svd1b.tmp

[1]+ Done ls /tmp


➤➤ pipefail — This is an alternative to the PIPESTATUS variable; if off (which is the default), the return code of a pipeline will be that of the rightmost command that returned a non-zero exit status. So, if you have a pipeline that fails part way through (you have no IP addresses here starting with 192.167, so the grep fails, but the cat and cut commands work fine), it is dif- ficult to tell if grep succeeded or not:

$ cat /etc/hosts | grep 192.167 | cut -f1

$ echo $?


The cut command succeeded, so you get a return code of zero (indicating success), which is probably not really what you want. However, when you set pipefail, you detect the error from any of the commands in the pipeline:

$ set -o pipefail

$ cat /etc/hosts | grep 192.167 | cut -f1

$ echo $?



➤➤ -o vi — This changes from emacs to vi mode.

➤➤ -x — This displays every command before it executes it. This is particularly useful in debugging shell scripts: #!/bin/sh -x at the start of the script, or set -x in the script (set +x disables it again), or even sh -x See also the BASH_XTRACEFD variable later in this sec- tion. Each line is preceded by the value of the PS4 variable, which is “+” by default:

$ cat


echo “Hello, world!”

if [ “$?” -eq “0” ]; then

# comments are ignored

echo “Hurray, it worked!”


echo “Oh no, echo failed!”


$ sh -x

+ echo Hello, world! Hello, world!

+ [ 0 -eq 0 ]

+ echo Hurray, it worked! Hurray, it worked!


You can see here that the test [ “$?” -eq “0” ] is expanded with the values, so the test being evaluated is [ 0 -eq 0 ].

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.