How to ensure a script can only be invoked from another?

Hi All,

I have two scripts - ScriptA and ScriptB

ScriptA has logic to invoke ScriptB :

  • with some parameter
  • or without any parameter

ScriptB can also be invoked by the user from the command line.

Is there anyway to ensure that when I execute ScriptB from the command line, it does not work and shows an error saying that ScriptB cannot be run automatically but can only be invoked via ScriptA?

Thanks In Advance.

Depending on just how complex you need to get, it could be as simple as setting an environment variable in scriptA and checking for it in scriptB.

export Xppid=$$               # script A exports it's pid

and in scriptB:

if [[ "$Xppid" != "$PPID" ]]
then
   echo "cannot run, not invoked by scriptA"
   exit 1
fi

Of course, the user could export their PID just like the script, but if you aren't concerned with users trying to skirt the system, then this is easy and it does the trick. There might be other, more "secure," methods, but my brain isn't coming up with any at the moment.

Please post what Operating System and version you have and what Shell you are using.

Ps. agama's solution is neat.
We use a similar solution with a manadatory parameter $1 such that the script exits with an error if the script is not invoked with that parameter.
Paying proper use of file permissions on script files also helps. Make use of groups.

We could combine these two methods and test for:

if [ "$1" != "$PPID" ]
then
   echo "cannot run, not invoked by scriptA"
   exit 1
fi

and call scriptB from scriptA like this:

/path/to/dir/scriptB $$

But this is just a tiny difference of course.

We could also test ps output if the PPID has a command field that shows the script name. but I don't think this is universal across implementations..