- Published on
How to Check If the Shell Script Is Running in Bash or Zsh
- Authors
- Name
- Ashik Nesin
- @AshikNesin
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
zsh custom_script.sh
elif [ -n "`$SHELL -c 'echo $BASH_VERSION'`" ]; then
# assume Bash
sh custom_script.sh
else
# something else like fish
fi
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