I'm trying to write a function to replace the functionality of the exit
builtin to prevent myself from exiting the terminal.
I have attempted to use the SHLVL
environment variable but it doesn't seem to change within subshells:
$ echo $SHLVL
1
$ ( echo $SHLVL )
1
$ bash -c 'echo $SHLVL'
2
My function is as follows:
exit () {
if [[ $SHLVL -eq 1 ]]; then
printf '%s\n' "Nice try!" >&2
else
command exit
fi
}
This won't allow me to use exit
within subshells though:
$ exit
Nice try!
$ (exit)
Nice try!
What is a good method to detect whether or not I am in a subshell?
$SHLVL
keeps track of what level you are at. anything more than 1 would be a subshell. – kemotep Jun 12 '19 at 18:41SHLVL
idea from but unfortunately it doesn't work from a subshell only a new bash invocation. @kemotep if you look at the example at the top of my question you can see thatSHLVL
in fact does not work. – jesse_b Jun 12 '19 at 18:42(...)
inherit all the properties of the parent process. The answers provided are more robust solutions to determining your shell level. – kemotep Jun 12 '19 at 18:52BASH_SUBSHELL
answer (even if controversial) wouldn't apply to that question. – Sparhawk Jun 13 '19 at 09:39