How to forbid script execution from different directory

Today I have found an interesting issue as I tried to forbid shell script execution from different directory.

Shell script

Solution is self-explanatory and presented below for your convenience.

#!/bin/sh
# simple shell script to demonstrate simple protection system
# as it cannot be executed from different directory

if [ "$(pwd)" != "$(dirname $(readlink -f  $0))" ]; then
  echo "Do not run $(basename $0) script from outside of the $(dirname $(readlink -f  $0)) directory"
  exit
fi

echo "Test passed"

Example

Store the above-mentioned shell script.

$ vi /tmp/test.sh

Execute shell script inside its location.

$ cd /tmp
$ sh test.sh
Test passed

Execute shell script outside of its location.

$ cd
$ sh /tmp/test.sh
Do not run test.sh script from outside of the /tmp directory

As you can see, it is a simple and straightforward solution and also perfect example of the basename, dirname and readlink command usage.

Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.

Gdansk, Poland https://sleeplessbeastie.eu