7

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
Quincy Glenn
  • 319
  • 4
  • 13
  • Why do you want to do that? A clever sysadmin could easily write some small C program to wrap the inner shell script. – Basile Starynkevitch Jan 14 '16 at 21:23
  • `./child.sh` runs the child script as an external executable in its own right, with its own interpreter -- just the same as if any other program had called an external executable. You can of course do something ugly and fragile like looking up your parent PID in the process tree, but see again re: ugly-and-fragile. – Charles Duffy Jan 14 '16 at 21:25
  • 1
    ...if your real goal is something different, ie. to detect interactive vs scripted invocation, there are better ways to do that (for instance, scripted invocations won't typically have a TTY unless that parent script is itself invoked by a user). Similarly, if you want to support something like a noninteractive batch mode, good form is to have that toggle be explicit, if not via an argument then by an environment variable, optionally with automatic enablement with no TTY present. – Charles Duffy Jan 14 '16 at 21:27

1 Answers1

4

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643