I would like to set -x temporarily in my script and then return in to the original state.
Is there a way to do it without starting new subshell? Something like
echo_was_on=....... ... ... if $echo_was_on; then set -x; else set +x; fi
You can simply do a echo $? after executing the command/bash which will output the exit code of the program. Every command returns an exit status (sometimes referred to as a return status or exit code).
We use the set command to change the values of shell options and display variables in Bash scripts. We can also use it to debug Bash scripts, export values from shell scripts, terminate programs when they fail, and handle exceptions. The set command has the following format: $ set [option] [argument]
Set –e is used within the Bash to stop execution instantly as a query exits while having a non-zero status. This function is also used when you need to know the error location in the running code.
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
You can check the value of $-
to see the current options; if it contains an x, it was set. You can check like so:
old_setting=${-//[^x]/} ... if [[ -n "$old_setting" ]]; then set -x; else set +x; fi
In case it's not familiar to you: the ${}
above is a Bash Substring Replacement, which takes the variable -
and replaces anything that's not an x
with nothing, leaving just the x
behind (or nothing, if there was no x)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With