How to get shell to self-detect using zsh or bash How to get shell to self-detect using zsh or bash bash bash

How to get shell to self-detect using zsh or bash


If the shell is Zsh, the variable $ZSH_VERSION is defined. Likewise for Bash and $BASH_VERSION.

if [ -n "$ZSH_VERSION" ]; then   # assume Zshelif [ -n "$BASH_VERSION" ]; then   # assume Bashelse   # assume something elsefi

However, these variables only tell you which shell is being used to run the above code. So you would have to source this fragment in the user's shell.

As an alternative, you could use the $SHELL environment variable (which should contain absolute path to the user's preferred shell) and guess the shell from the value of that variable:

case $SHELL in*/zsh)    # assume Zsh   ;;*/bash)   # assume Bash   ;;*)   # assume something elseesac

Of course the above will fail when /bin/sh is a symlink to /bin/bash.

If you want to rely on $SHELL, it is safer to actually execute some code:

if [ -n "`$SHELL -c 'echo $ZSH_VERSION'`" ]; then   # assume Zshelif [ -n "`$SHELL -c 'echo $BASH_VERSION'`" ]; then   # assume Bashelse   # assume something elsefi

This last suggestion can be run from a script regardless of which shell is used to run the script.


Just do echo $0it says -zsh if it's zsh and -bash if it's bash

EDIT: Sometimes it returns -zsh and sometimes zsh and the same with bash, idk why.


A word of warning: the question you seem to have asked, the question you meant to ask, and the question you should have asked are three different things.

“Which shell the user is using” is ambiguous. Your attempt looks like you're trying to determine which shell is executing your script. That's always going to be whatever you put in the #! line of the script, unless you meant your users to edit that script, so this isn't useful to you.

What you meant to ask, I think, is what the user's favorite shell is. This can't be determined fully reliably, but you can cover most cases. Check the SHELL environment variable. If it contains fish, zsh, bash, ksh or tcsh, the user's favorite shell is probably that shell. However, this is the wrong question for your problem.

Files like .bashrc, .zshrc, .cshrc and so on are shell initialization files. They are not the right place to define environment variables. An environment variable defined there would only be available in a terminal where the user launched that shell and not in programs started from a GUI. The definition would also override any customization the user may have done in a subsession.

The right place to define an environment variable is in a session startup file. This is mostly unrelated to the user's choice of shell. Unfortunately, there's no single place to define environment variables. On a lot of systems, ~/.profile will work, but this is not universal. See https://unix.stackexchange.com/questions/4621/correctly-setting-environment and the other posts I link to there for a longer discussion.