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?
(...)
inherit all the properties of the parent process. The answers provided are more robust solutions to determining your shell level.BASH_SUBSHELL
answer (even if controversial) wouldn't apply to that question.