I want to how to determine if a script file is executed or sourced.
For example,
# Shell script filename build.sh
if [ "x$0" = "xbash" ]; then
echo "I am sourced by Bash"
else
echo "I am executed by Bash"
fi
If I typed
source build.sh
it would output I am sourced by Bash.
If I typed
./build.sh
it would output I am executed by Bash.
Currently, I use $0 to do this. Is there a better idea?
Inspired by Tripeee, I found a better way:
#!/bin/bash
if [ "x$(awk -F/ '{print $NF}' <<< $0)" = 'xcdruntime' ]; then
echo Try to source me, not execute me.
else
cd /opt/www/app/pepsi/protected/runtime
fi
It doesn't work if sourced by another script. I would go the other way around;
test "X$(basename -- "$0")" = "Xbuild.sh" || echo Being sourced
Update: added X prefix to both strings.
Update too: added double dash to basename
invocation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With