Greg Rynkowski
Greg Rynkowski

Reputation: 566

How to detect shell options enabled

set allows tweaking shell execution, by enabling some features. Some of the most popular are:

set -e   # exit on error
set -x   # print executed commands

Is there a way within a script to detect currently enabled features?

In my particular case I would like to know if the set -x was called.

Upvotes: 0

Views: 724

Answers (3)

Jetchisel
Jetchisel

Reputation: 7791

The builtin shopt can probably show what you wanted.

In man bash

errexit Same as -e

Now

help shopt

Output

shopt: shopt [-pqsu] [-o] [optname ...]
    Set and unset shell options.
    
    Change the setting of each shell option OPTNAME.  Without any option
    arguments, list each supplied OPTNAME, or all shell options if no
    OPTNAMEs are given, with an indication of whether or not each is set.
    
    Options:
      -o        restrict OPTNAMEs to those defined for use with `set -o'
      -p        print each shell option with an indication of its status
      -q        suppress output
      -s        enable (set) each OPTNAME
      -u        disable (unset) each OPTNAME
    
    Exit Status:
    Returns success if OPTNAME is enabled; fails if an invalid option is
    given or OPTNAME is disabled.

shopt -qo errexit

echo $?

It returns 1 if disabled or 0 if enabled.

Now to have an actual test.

if shopt -qo errexit; then
  printf 'errexit is enabled!\n'
fi

Or if you want to negate use the bang !

if ! shopt -qo errexit; then
  printf 'errexit is disabled!\n'
fi

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246837

Use the $- variable:

$ echo $-
himBCHs

$ set -e
$ set -x

$ echo $-
ehimxBCHs
^   ^

So:

if [[ $- == *x* ]]; then
    echo "xtrace is set"
fi

Upvotes: 4

Antonio Petricca
Antonio Petricca

Reputation: 11026

The command set -o prints all the configured bash options.

Upvotes: 1

Related Questions