How can I determine the current shell I am working on?
Would the output of the ps
command alone be sufficient?
How can this be done in different flavors of Unix?
There are three approaches to finding the name of the current shell's executable:
Please note that all three approaches can be fooled if the executable of the shell is /bin/sh
, but it's really a renamed bash
, for example (which frequently happens).
Thus your second question of whether ps
output will do is answered with "not always".
echo $0
- will print the program name, which in the case of an interactive shell is often the shell's name. But this can be changed by the user, e.g. sh -c 'echo $0' not-a-shell
. And in a script, it's usually the filename of the script, not the shell.
ps -p$$
- this show the command associated with the current process (the shell). This seems less susceptible to user change (but see next section on heuristics).
echo $SHELL
- The path to the user's preferred shell is stored as the SHELL
variable by the login
program. But we don't know that the running shell is the user's preferred shell, so this one doesn't work at all.
If the executable doesn't match your actual shell (e.g. /bin/sh
is actually bash or ksh), you need heuristics. Here are some environmental variables specific to various shells:
$version
is set on tcsh
$BASH
is set on bash
$shell
(lowercase) is set to actual shell name in csh or tcsh
$ZSH_NAME
is set on zsh
ksh has $PS3
and $PS4
set, whereas the normal Bourne shell (sh
) only has $PS1
and $PS2
set. This generally seems like the hardest to distinguish - the only difference in the entire set of environment variables between sh
and ksh
we have installed on Solaris boxen is $ERRNO
, $FCEDIT
, $LINENO
, $PPID
, $PS3
, $PS4
, $RANDOM
, $SECONDS
, and $TMOUT
.
Someone brought up "ash
" (Almquist Shell) in comments. There seem to be 2001 variants of it including dash
; so in the interest of not blowing up the answer unnecessarily, here's a very useful page listing a ton of various flavours of ash
and their differences from each other and often from standard Bourne sh
.