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.

# 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"
echo "Test passed"


Store the above-mentioned shell script.

$ vi /tmp/

Execute shell script inside its location.

$ cd /tmp
$ sh
Test passed

Execute shell script outside of its location.

$ cd
$ sh /tmp/
Do not run 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.