I am accidentally caught in a desire to reveal the subshell number (BASH_SUBSHELL) from within the script itself, but i get subshell 0

Here is the script's line

echo "Operated from subshell: $BASH_SUBSHELL

Part of the shell's output in terminal

  • echo 'Operated from subshell: 0' Operated from subshell: 0

Question Is it possible to reveal the subshell a script is operating from within the script itself?

  • 1
    Scripts don't run in subshells, so this output looks correct to me. What are you expecting? – Michael Homer Apr 23 at 21:27
  • @jim-chriss, Michael is right: executing a shell script runs that script is a separate process, not as a subshell of your interactive shell. – glenn jackman Apr 23 at 21:31
  • @Michael Homer shell scripts do run in subshells if invoked using their names in terminal, I quote the tldp book page 28, says "This is the most common way to execute a script. It is preferred to execute the script like this in a subshell." – Jim-chriss Charles Apr 24 at 8:25
  • No, they don't. – Michael Homer Apr 24 at 8:27
  • I will acknowledge that the book does say that, and that it does so because the book is incompetently written. – Michael Homer Apr 24 at 8:29

Since scripts do not run in subshells, this output is correct. Subshells are created by a few things, including parentheses ( ... ), backgrounding with &, and command substitution $( ... ), but not by launching scripts: that creates a whole new shell to execute the script in.

What you may be thinking of is the SHLVL variable, which does increment for each layer of script (and shell):

SHLVL Incremented by one each time a new instance of Bash is started. This is intended to be a count of how deeply your Bash shells are nested.

If your script line were

echo "Operated from shell level: $SHLVL"

then you would get the output that I think you expected. If the script recursed, $SHLVL would increment each time.

  • Bash Guide for Beginners, on page 28, says invoking a script as willy:~> script1.sh is ... I quote "This is the most common way to execute a script. It is preferred to execute the script like this in a subshell. The variables, functions and aliases created in this subshell are only known to the particular bash session of that subshell. When that shell exits and the parent regains control, everything is cleaned up and all changes to the state of the shell made by the script, are forgotten." – Jim-chriss Charles Apr 24 at 8:28

Here's some code that actually uses some subhells:

echo "main shell: $BASH_SUBSHELL"
    echo "first subshell: $BASH_SUBSHELL"
        echo "second subshell: $BASH_SUBSHELL"
            echo "third subshell: $BASH_SUBSHELL"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.