Sandeep Sandeep -4 years ago 110
Bash Question

bash if comparison fails when script is sourced

Below is the mwe which reads an input and
compares with character 'a'.
It works fine when invoked as it is.

read -n 1 inp
if [ $inp = 'a' ]
then
echo "Hello"
fi


However, when sourced it gives
error:

parse error: condition expected: =

Answer Source

This happens because the script you source it from runs with zsh, not bash.

Sourced scripts are always run with the shell that does the sourcing, regardless of shebang. Your script is written for bash and is incompatible with zsh, so it fails.

The equivalent zsh code is:

read  -k 1  inp
if [ "$inp" = 'a' ]
then
    echo "Hello"
fi
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download