如果用户当前不在 shell 脚本目录中,我想暂停我的 shell 脚本。例如,我在文件夹中~/
并调用 shell 脚本~/shell/script.sh
,则 shell 脚本应该打印You are not allowed to call this shell script from another folder other than its directory
。但如果我在文件夹中~/shell
并调用,./script.sh
则允许执行。
你为什么关心是什么
$PWD
?如果重要的话,你可以在脚本中更改目录:cd "$(dirname "$0")"
这是一个非常局部攻击性/危险的脚本,所以我希望用户在运行脚本时能够在文件夹中更加关注它。
相关问题:
答案1
realpath
您可以使用解析隐式当前目录来获取执行脚本的完整路径(man realpath
有关详细信息,该-P
选项很有用):
mydir=$(dirname $(realpath $0))
[[ $PWD != $mydir ]] && { echo "Not in the right directory!"; exit 1; }
echo "OK, proceed..."
答案2
谢谢@grawity,我写了这个:
# 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