You may not want to know the current shell's name (e.g. -bash
, bash
, zsh
, etc., from echo $0
), nor default shell's executable path (from echo $SHELL
), but rather the current shell's executable path (especially useful e.g. if you have more than one version of Bash installed).
To do this you can use lsof -p "$$"
or with some extra coding to extract just the required info:
lsof -p "$$" | grep -m 1 txt | xargs -n 1 | tail -n 1
Example output for Bash installed via Homebrew:
/usr/local/Cellar/bash/5.1.8/bin/bash
or for Zsh:
/bin/zsh
The above is different from echo $SHELL
, both because the above is for the shell which is currently running rather than the user's default shell, and also because the above gives the executable after any symlinks have been expanded. E.g. for the same Bash install as above, echo $SHELL
gives /usr/local/bin/bash
.
EDIT 1: If you need to allow for possible space characters in the shell's path, use lsof -p "$$" | grep -m 1 txt | xargs -n 1 | tail -n +9 | xargs
instead.
EDIT 2: Yet another way to see the current shell's executable, this time not using lsof
, is ls -l "/proc/$$/exe"
.
Converting this to a command which doesn't require lsof
, allows for possible spaces in the shell executable path and allows for possible aliases of ls
, we get:
"$(which ls)" -l "/proc/$$/exe" | xargs -n 1 | tail -n +11 | xargs
Note that this last version with /proc/$$
does not work on macOS, whereas the versions with lsof
do, as well as on any Linux with lsof
installed.