1

A lot of times I will used wrapper scripts for projects to maintain environment variables during development;

shell.sh:

#!/bin/bash
export PATH=$PWD/bin:$PATH
export USERNAME=foo
export PASSWORD=bar
export DB_SERVER=http://localhost:6001
bash

This sets the environment for the project then starts an interactive bash session. This example is a shell script but actually I do this most often from within a similarly configured Makefile recipe, if it matters.

The problem is that when I am inside these sessions, its often difficult to distinguish it visually from my session outside of the project environment. Its also possible to accidentally run such script multiple times and thus be running inside multiple levels of nested bash sessions.

I was hoping that there might be a way to display in my command prompt some value that could indicate how many times bash has been invoked so I can tell more easily if I am in a bash sub-session or if I am in the parent bash session.

I saw some bash variables listed here: https://www.gnu.org/software/bash/manual/bash.html#Bourne-Shell-Variables

in particular there is BASH_SUBSHELL which counts the subshell levels, but since this is not actually a subshell it does not work for this purpose:

$ (echo $BASH_SUBSHELL)
1
$ (echo $BASH_SUBSHELL; bash)
1
$ echo $BASH_SUBSHELL
0

Is there some other way to maintain a counter of this? If so, I could easily stick something in my bash prompt to show this more clearly in my terminal.


here is a comparison of different methods based on the comments, using the script above:

# inside top-level parent session
$ echo $$ $BASHPID $BASH_SUBSHELL $SHLVL
32336 32336 0 1

# invoke the script to enter a new bash session
$ ./test.sh

$ echo $$ $BASHPID $BASH_SUBSHELL $SHLVL
39541 39541 0 3

$BASH_SUBSHELL does not reflect the new shell level

10
  • 2
    Perhaps $SHLVL is what you want? see for example Why does the value of BASH_SUBSHELL not change while the value of SHLVL changes? Jan 3, 2020 at 15:59
  • looks like the $SHLVL one works, if you want to make that an answer @steeldriver. I tried the ones comparing the bash process ID values but they did not seem to be working either, I think because its not a true 'subshell' invoked with () Jan 3, 2020 at 16:03
  • also strangely, $SHLVL increases by 2 every time I run this kind of script Jan 3, 2020 at 16:07
  • 2
    @user5359531: The script itself is a child shell then you execute bash inside it creating another child shell.
    – jesse_b
    Jan 3, 2020 at 16:09
  • 3
    To avoid having SHLVL increase by 2, use exec bash instead of just bash.
    – Kusalananda
    Jan 3, 2020 at 16:16

0

Browse other questions tagged .