Linux: How to detect the current shell inside a script

This seems obvious, right? You just do:

echo $SHELL

and that’s it, correct?

Nope, that gives you the user’s default shell. If the user’s shell is bash, and a script has a shebang (#!) in the first line to specify a different shell (e.g. #!/bin/ksh), the above will say it’s “/bin/bash“. And that’s not what we want here.

Some quick googling was in order, and most suggestions were either:

echo $0


ps -p $$

These work fine in an interactive shell… but inside a script, they’ll reply with the script‘s path, not the shell.

Finally, I found one which worked. It requires /proc, which may not exist in some Unixes, but, AFAIK, it’s mostly universal in Linux:

readlink /proc/$$/exe

So, if, for instance, a user’s default shell is bash, the script:

readlink /proc/$$/exe

will reply (correctly) with something like (on a Red Hat 8.x system; other distros may have different versions of ksh and/or paths, by default):


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: