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
$PWDis? 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:
2 Answers 2
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
# https://stackoverflow.com/questions/12815774/importing-functions-from-a-shell-script
if ! [[ -z "0ドル" ]]
then
# 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
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
You must log in to answer this question.
Explore related questions
See similar questions with these tags.
$PWD.cd "$(dirname "$(realpath "0ドル")")"0ドルcontains the current file file on the form./shell.sh, as later on the shell script, I am usingfind .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 applyingsed .