Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a shell script is called from another shell script [duplicate]

Tags:

linux

bash

shell

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
like image 873
Quincy Glenn Avatar asked Jan 14 '16 21:01

Quincy Glenn


1 Answers

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.

like image 86
anubhava Avatar answered Oct 17 '22 14:10

anubhava