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
How to execute scripts in a parent-child behavior in bash?
shell script;process
Here is one way to achieve it:$ cat parent.sh#!/bin/shecho parent.sh running./child.sh$ cat other.sh#!/bin/shecho other.sh running./child.sh$ cat child.sh#!/bin/shparent=$(ps -o comm= -p $PPID)if [ $parent != parent.sh ]; then    echo this script should be directly executed by parent.sh, not by $parent    exit 1fiecho child.sh proceeding$ ./parent.shparent.sh runningchild.sh proceeding$ ./other.shother.sh runningthis script should be directly executed by parent.sh, not by other.shNote 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.