Is there a way to detect if a shell script is called directly or called from another script.
parent.sh
#/bin/bash
echo "parent script"
./child.sh
child.sh
#/bin/bash
echo -n "child script"
[ # if child script called from parent ] && \
echo "called from parent" || \
echo "called directly"
results
./parent.sh
# parent script
# child script called from parent
./child.sh
# child script called directly
You can use child.sh
like this:
#/bin/bash
echo "child script"
[[ $SHLVL -gt 2 ]] &&
echo "called from parent" ||
echo "called directly"
Now run it:
# invoke it directly
./child.sh
child script 2
called directly
# call via parent.sh
./parent.sh
parent script
child script 3
called from parent
$SHLVL
is set to 1
in parent shell and will be set to more than 2 (depends on nesting) when your script is called from another script.
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