M HYPE SPLASH
// general

How to block shell script from being called elsewhere other than the folder it is on?

By Michael Henderson

I would like to halt my shell script if the user is currently not the shell script directory. For example, I am on the folder ~/ and call the shell script ~/shell/script.sh, the shell script should print You are not allowed to call this shell script from another folder other than its directory. But if I am on the folder ~/shell and call ./script.sh than the execution is allowed.

Why do you care what the $PWD is? You can change directories in the script if it matters: cd "$(dirname "$0")"

It is a very local aggressive/dangerous script, so I would like the user to be present on the folder paying more attention on it when it is running the script.


Related questions:

  1. Check if bash script was invoked from a shell or another script/application
  2. Executable lauches if called directly from terminal, but does not work when called from shell script
5

2 Answers

You can get the full path to your executing script by using realpath to resolve the implicit current directory (man realpath for details, the -P option can be useful):

mydir=$(dirname $(realpath $0))
[[ $PWD != $mydir ]] && { echo "Not in the right directory!"; exit 1; }
echo "OK, proceed..."

Thanks @grawity, I wrote this:

# Call the main function, as when running from the command line the `$0` variable is
# not empty.
#
# Importing functions from a shell script
#
if ! [[ -z "$0" ]]
then # Reliable way for a bash script to get the full path to itself? # pushd `dirname $0` > /dev/null SCRIPT_FOLDER_PATH=`pwd` popd > /dev/null if[[ "$SCRIPT_FOLDER_PATH" == "$(pwd)" || "$SCRIPT_FOLDER_PATH" == "$(dirname "$0")" ]] then main "$@" else printf "You cannot run this from the folder: \n'$(pwd)'\n" printf "\nPlease, run this script from its folder on: \n'$SCRIPT_FOLDER_PATH'\n" fi
fi

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy