As @John Kugelman says, echo $SHLVL
will tell you the bash shell depth.
And as @Dennis Williamson shows, you can edit your prompt via the PS1
variable to get it to print this value.
I prefer that it always prints the shell depth value, so here's what I've done: edit your ~/.bashrc
file:
gedit ~/.bashrc
and add the following line to the end:
export PS1='\$SHLVL'":$SHLVL\n$PS1"
Now you will always see a printout of your current bash level just above your prompt. Ex: here you can see I am at a bash level (depth) of 2, as indicated by the $SHLVL:2
:
$SHLVL:2
7510-gabriels ~ $
Now, watch the prompt as I go down into some bash levels via the bash
command, then come back up via exit
. Here you see my commands and prompt (response), starting at level 2 and going down to 5, then coming back up to level 2:
$SHLVL:2
7510-gabriels ~ $ bash
$SHLVL:3
7510-gabriels ~ $ bash
$SHLVL:4
7510-gabriels ~ $ bash
$SHLVL:5
7510-gabriels ~ $ exit
exit
$SHLVL:4
7510-gabriels ~ $ exit
exit
$SHLVL:3
7510-gabriels ~ $ exit
exit
$SHLVL:2
7510-gabriels ~ $
Bonus: always show in your terminal your current git branch
you are on too!
Make your prompt also show you your git branch you are working on by using the following in your "~/.bashrc" file instead:
git_show_branch() {
__gsb_BRANCH=$(git symbolic-ref -q --short HEAD 2>/dev/null)
if [ -n "$__gsb_BRANCH" ]; then
echo "$__gsb_BRANCH"
fi
}
export PS1="\e[7m\$(git_show_branch)\e[m\n\h \w $ "
export PS1='\$SHLVL'":$SHLVL $PS1"
Source: I have no idea where git_show_branch()
originally comes from, but I got it from Jason McMullan on 5 Apr. 2018. I then added the $SHLVL
part shown above just last week.
Sample output:
$SHLVL:2 master
7510-gabriels ~/GS/dev/temp $
And here's a screenshot showing it in all its glory. Notice the git branch name, master
, highlighted in white!

My latest PS1
prompt
I've improved my PS1
prompt again and put it in my eRCaGuy_dotfiles repo. It is inside my ~/.bash_aliases
file, which is sourced by my ~/.bashrc
file. Search my ~/.bash_aliases
file for both my PS1
entries and the gs_git_show_branch_and_hash
function used by them.
Here's a sample output of the new terminal prompt. Notice how it shows the shell level as 1
, and it shows the branch name of the currently-checked-out branch (master
in this case), as well as its short git hash (bac27c7
in this case), whenever I'm inside a local git repo!:

This is really helpful to help me ensure I'm always performing my git
operations on the correct branch, and to automatically see whenever I cd
into a Git repository.
Cross-referenced: