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
  • 3
    Your own question already answers this in the 2nd paragraph – you can compare $PWD. – user1686 Aug 6 '17 at 12:58
  • Second paragraph is a comment from this deleted question. – Cyrus Aug 6 '17 at 13:05
  • 1
  • Why don't you just have the script change directory to its own directory? Then it doesn't matter where you call it from: cd "$(dirname "$(realpath "$0")")" – glenn jackman Aug 6 '17 at 16:09
  • Because I need to ensure the $0 contains the current file file on the form ./shell.sh, as later on the shell script, I am using find . to list the files on the current folder and with "$path" != "$0" is how I choose to exclude the own shell script from this processing list I am applying sed . – user Aug 6 '17 at 17:45

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..."
|improve this answer|||||

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
# https://stackoverflow.com/questions/12815774/importing-functions-from-a-shell-script
if ! [[ -z "$0" ]]
    # Reliable way for a bash script to get the full path to itself?
    # http://stackoverflow.com/questions/4774054/reliable-way-for-a-bash-script-to-get
    pushd `dirname $0` > /dev/null
    popd > /dev/null

    if[[ "$SCRIPT_FOLDER_PATH" == "$(pwd)" || "$SCRIPT_FOLDER_PATH" == "$(dirname "$0")" ]]
        main "$@"
        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"
|improve this answer|||||

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.