Linux: How to detect the current shell inside a script

This seems obvious, right? You just do:

[pastacode lang=”bash” manual=”echo%20%24SHELL” message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”bash” manual=”echo%20%240″ message=”” highlight=”” provider=”manual”/]

or:

[pastacode lang=”bash” manual=”ps%20-p%20%24%24″ message=”” highlight=”” provider=”manual”/]

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:

[pastacode lang=”bash” manual=”readlink%20%2Fproc%2F%24%24%2Fexe%0A” message=”” highlight=”” provider=”manual”/]

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

[pastacode lang=”bash” manual=”%23!%2Fbin%2Fksh%0Areadlink%20%2Fproc%2F%24%24%2Fexe” message=”” highlight=”” provider=”manual”/]

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

/usr/bin/ksh93

Leave a Reply

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