How to execute scripts in a parent-child behavior in bash? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to execute scripts in a parent-child behavior in bash? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Suppose I have two scripts named parent.sh and child.sh. The parent.sh script contains bash child.sh line and the child.sh script contains echo "This is the child script".

Now, if the user executes the parent.sh, it should simply call the child.sh script and exit. But if the user executes the child.sh script, it should produce some error saying only parent.sh can execute the child.sh script.

Is there a way that I can achieve this type of behaviour of executing the scripts? This was just a small example, I have a huge set of scripts which a user can execute but these scripts should only be executed by the parent script.

This is just to make sure that the user doesn’t executes the wrong script by mistake. I don’t want to strip away the users read/write permissions.

My requirements in a nut shell:

bash parent.sh -> execute bash child.sh -> execute something by child.sh

Answer

Here is one way to achieve it:

$ cat parent.sh
#!/bin/sh

echo parent.sh running

./child.sh

$ cat other.sh
#!/bin/sh

echo other.sh running

./child.sh

$ cat child.sh
#!/bin/sh

parent="$(ps -o comm= -p $PPID)"

if [ "$parent" != parent.sh ]; then
    echo this script should be directly executed by parent.sh, not by $parent
    exit 1
fi

echo "child.sh proceeding"

$ ./parent.sh
parent.sh running
child.sh proceeding

$ ./other.sh
other.sh running
this script should be directly executed by parent.sh, not by other.sh

Note that this is only checking if the immediate parent process is the expected one. If you need to go deeper in the process hierarchy, you need to adapt the script to climb the parent relationship.

An alternate way might be to export a custom variable and check if it is set in the child processes.

Neither of these methods are really secure as there are simple ways to fake a process name or set whatever variable.

We are here to answer your question about How to execute scripts in a parent-child behavior in bash? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji