Menu

DevOps Simplified…

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):

➤➤ 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 $?

0

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 $?

1

$

➤➤ -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 myscript.sh 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 x.sh

#!/bin/bash

echo “Hello, world!”

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

# comments are ignored

echo “Hurray, it worked!”

else

echo “Oh no, echo failed!”

fi

$ sh -x x.sh

+ 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 ].