Categories
bash

$SHELL: The $0-sum Game

Q: Which shell am I currently running?
A: $SHELL.

NOPE.

The SHELL environment variable has a very specific meaning. Here’s what the POSIX standard has to say about it:

SHELL
This variable shall represent a pathname of the user’s preferred command language interpreter.

For every shell I’ve ever used, that highlighted phrase has been interpreted as the user’s login shell, which may not be relevant to the currently-running environment. For instance, cron specifically forces $SHELL in all cron jobs to /bin/sh by default, ostensibly for sanity and/or security reasons.

Also:

~ $ echo $SHELL
/bin/bash
~ $ zsh
~ % echo $SHELL
/bin/bash

In everyday scripting, $SHELL should only ever be used to answer one question: “What shell should my process spawn if necessary?

And so we return to the original question…

Q: Which shell am I currently running?
A: $0 from the command line.

~ $ echo $0
-bash
~ $ zsh
~ % echo $0
zsh

But I want to know what shell is running my script in the script itself. How do I do that?

On Linux, you could run this code snippet (credit: Evan Benn):

sh -c 'ps -p $$ -o ppid=' | xargs -I'{}' readlink -f '/proc/{}/exe'

But a much better way of going about it is to first ask yourself why you need to know. If, as is almost always the case, you want to do something that’s shell-specific, then simply test for a variable that’s unique to your desired shell (e.g. $BASH, $ZSH_NAME), then execute the desired code accordingly. Easy peasy.

Leave a Reply

Your email address will not be published. Required fields are marked *