1

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

1 Answer 1

3

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .