POSIX sh check (test) value of builtin set option

Viewed 111

In POSIX sh you may set options with set:

#!/bin/sh

set -u;

echo "$notset";

that gives expected:

parameter not set or null

but how to check if option -e is set or not?

I want at some point of my script to turn it off but set it back to on only if it was previously on.

2 Answers

The shell options are held in $- as a string of single characters. You test for -e with

case $- in
(*e*)    printf 'set -e is in effect\n';;
(*)      printf 'set -e is not in effect\n';;
esac

Following the accepted answer I did this:

to store option state (empty string = off, option char = on)

option="e"
option_set="$(echo $- | grep "$option")"

to restore it to previous value stored in option_set in case I modified its state:

if [ -n "$option_set" ]; then 
    set -"$option"
else 
    set +"$option" 
fi

here's a test script if you'd like to play with that solution:

#!/bin/sh

return_non_zero() {
    echo "returing non zero"
    return 1
}

set -e # turn on option
# set +e # turn off option

echo "1. options that are set: $-"

option="e"
option_set="$(echo $- | grep "$option")"

echo "turn off "$option" option" && set +"$option"
# echo "turn on "$option" option" && set -"$option"

echo "2. options that are set: $-"

# should terminate script if option e is set
return_non_zero

# restore option to prev value
if [ -n "$option_set" ]; then 
    set -"$option"
else 
    set +"$option" 
fi

echo "3. options that are set: $-"

echo "END"
Related