Sample Header Ad - 728x90

How can I detect if I'm in a subshell?

38 votes
3 answers
10156 views
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?
Asked by jesse_b (41447 rep)
Jun 12, 2019, 06:35 PM
Last activity: May 8, 2024, 07:37 PM