bvk
bvk

Reputation: 39

zsh/bash source command behavior difference

I am trying to source a third party script in zsh (named setup_env.sh stored in ~/), that has following lines in the beginning to guard against accidental execution:

#!/bin/sh

# Guard the script against execution - it must be sourced!
echo $0 | egrep 'setup_env.sh' > /dev/null
if [ $? -eq 0 ]; then
echo ""
echo "ERROR: the setup file must be SOURCED, NOT EXECUTED in a shell."
echo "Try (for bash)  : source setup_env.sh"
echo "Or (eg. for ksh): . setup_env.sh"
exit 1
fi

# export some environment variables
...

When I source this script with source ~/setup_env.sh, I see the error message shown in the above code block.

From the script it's apparently visible that it's not written with zsh in mind. But I still want to know why zsh behaves this way, and if it's possible to source the script as it is.

I could source the script as it is without error using bash. I could also source it in zsh after commenting out the guard block in the beginning of the script.

Can someone explain this difference in behavior for source command between zsh and bash?

Upvotes: 0

Views: 1372

Answers (1)

Philippe
Philippe

Reputation: 26810

zsh/bash have different ways to detect sourcing, following should work for both :

if  [[ -n  $ZSH_VERSION && $ZSH_EVAL_CONTEXT == toplevel ]] || \
    [[ -n $BASH_VERSION && $BASH_SOURCE      == $0       ]]; then
    echo "Not sourced"
    exit 1
fi

To explain a little more, when you run :

source setup_env.sh
# setup_env.sh containing "echo $0"

In zsh, $0 == setup_env.sh

In bash, $0 == bash

Upvotes: 2

Related Questions