Short way to run command if variable is set

Instead of relying on the value of the variable to have an executable value (and a value that you want to be executed), define a function that simply checks if the value is set.

debug () [[ -v DEBUG ]]

debug && echo "Hello"

If DEBUG is set at all, even to the empty string, debug will succeed and the following command executes.

If DEBUG is not set and you want your script to run the debug commands, simply invoke it as

DEBUG= ./myscript

If DEBUG is set, you can unset it first.

unset DEBUG
./myscript

If the value of DEBUG really matters for whatever reason, then you can just test that it has a non-empty value instead of using -v:

debug () [[ -n $DEBUG ]]

To run your script in debug mode, pick an arbitrary non-empty value

DEBUG=1 ./myscript

To run your script in "real" mode even if DEBUG is current set in your environment, use

DEBUG= ./myscript

If you want to use the value:

[[ -n $DEBUG ]] && echo "Hello"

If you want to use the negation of the value:

[[ -z $DEBUG ]] && echo "Hello"

That's I think is the shortest. Note the $ in front of the variable name is required.

Tags:

Bash