Published on

How to Check If the Shell Script Is Running in Bash or Zsh


When we're writing a custom script we need to make sure that we're we need to make sure that our code runs properly in the shell in which we're running on.

For example, if we try to run [[ -f ~/.zshrc ]] && source ~/.zshrc; in bash shell it'll throw the following error.

Error: Oh My Zsh can't be loaded from: sh. You need to run zsh instead.

Here's how to handle it.

Snippet for finding current shell

if [ -n "`$SHELL -c 'echo $ZSH_VERSION'`" ]; then
   # assume Zsh
elif [ -n "`$SHELL -c 'echo $BASH_VERSION'`" ]; then
   # assume Bash
  # something else like fish

How does it work?

-n used to check the string next to it and returns true if the string is not empty.

'-c' executes the commands from the string

$SHELL would return /bin/zsh or /bin/bash depending on the shell that you're using.

And it tries to execute echo $ZSH_VERSION first. If we're are in bash then that statement gets executed. Similarly for bash shell we are checking for echo $BASH_VERSION