-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?

10
  • 1
    Scripts don't run in subshells, so this output looks correct to me. What are you expecting? Commented Apr 23, 2019 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. Commented Apr 23, 2019 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." Commented Apr 24, 2019 at 8:25
  • No, they don't. Commented Apr 24, 2019 at 8:27
  • I will acknowledge that the book does say that, and that it does so because the book is incompetently written. Commented Apr 24, 2019 at 8:29

2 Answers 2

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.

1
  • 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." Commented Apr 24, 2019 at 8:28
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"
        )
    )
)

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.