Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there way to check if shell script is executed with -x flag

Tags:

bash

shell

sh

I am trying to check in the script, that if that script is executed with -x flag which is for the debugging for shell scripts. Is there any way to check that in script itself that -x is set. I want to conditionally check that and do something if that is set.

like image 523
user3565529 Avatar asked Sep 01 '16 19:09

user3565529


3 Answers

Use:

if [[ $- == *x* ]]; then
  echo "debug"
else
  echo "not debug"
fi

From Bash manual:

($-, a hyphen.) Expands to the current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the -i option).

like image 138
Dave Grabowski Avatar answered Nov 03 '22 01:11

Dave Grabowski


The portable way to do this (without bashisms like [[ ]]) would be

case $- in
(*x*) echo "under set -x"
esac
like image 39
Jens Avatar answered Nov 02 '22 23:11

Jens


You can trap the DEBUG signal, like so:

trap "do_this_if_it_is_being_debugged" DEBUG

function do_this_if_it_is_being_debugged() {
...
}

Note this needs to be executed before the set -x is being executed

like image 45
creativeChips Avatar answered Nov 02 '22 23:11

creativeChips