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: 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.