0

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?

3
  • Probably because . and source in zsh support additional arguements, but it does not in bash or ksh. IMO that check is poorly implemented. Commented May 13, 2020 at 20:53
  • @jordanm Both bash and ksh support passing arguments to the sourced file. Commented May 14, 2020 at 15:35
  • The easiest fix would just be to strip that kind of hand-holding from the script. Commented May 14, 2020 at 15:36

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.