-2

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?

2 Answers2

0

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"
        )
    )
)
glenn jackman
  • 85,964
0

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.

Michael Homer
  • 76,565
  • 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 '19 at 08:28