Reputation: 403
I know bash can be set to verbose mode by using set -v
, however I want to write a function that doesn't run in verbose mode even if called from a verbosed script.
While I'm aware I could disable verbosity by using set +v
at the start of the function and end it with set -v
, that would mean my function will set any script that calls it to verbose, even if it wasn't verbose before calling it.
Ideally I'd check the verbosity level at the start of the function, disable verbosity, and revert the verbosity change at the end of the function.
Is there a way to find current verbosity level?
Upvotes: 2
Views: 1090
Reputation: 15613
if test -o verbose; then
echo 'shell is running in verbose mode'
else
echo 'shell is not running in verbose mode'
fi
or, equivalently,
if [[ -o verbose ]]; then
echo 'shell is running in verbose mode'
else
echo 'shell is not running in verbose mode'
fi
The built-in test
utility in bash
is able to test whether a shell option is set or not using -o OPTION
. See help test
in an interactive bash
shell, or read about it is the bash
manual.
Your function may look like
foo () {
if [[ -o verbose ]]; then
set +v
trap 'set -v' RETURN
fi
# do stuff
}
This detects whether -v
is active when the function is called. If it is, it is turned off and a RETURN
trap is installed that will switch it back on again when the function returns (at the end of the function, or by an explicit return
statement).
Upvotes: 1
Reputation: 123490
Depending on your function and its usage, you could just limit the scope of option changes with a (..)
subshell:
foo() (
set +vx
echo "not verbose"
)
set -v
foo
echo "still verbose"
Upvotes: 0
Reputation: 88654
if [[ $- =~ v ]]; then
echo "verbose enabled"
else
echo "verbose disabled"
fi
$-
: Contains the current set of enabled options. See:help set
Upvotes: 5
Reputation: 141155
Checking verbose mode option is the same as checking any other bash option, see In bash, how to get the current status of set -x? .
Try this:
func() {
local old_verbosity_level=${-//[^v]}
set +v
...
if [ -n "$old_verbosity_level" ]; then set -v; else set +v; fi
}
or more tricky:
func() {
local old_verbosity_level=${-//[^v]}
set +v
...
${old_verbosity_level:+set -v}
}
Upvotes: 0