如何阻止 shell 脚本在其所在文件夹之外的其他地方被调用?

如何阻止 shell 脚本在其所在文件夹之外的其他地方被调用?

如果用户当前不在 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. 检查 bash 脚本是否从 shell 或其他脚本/应用程序调用
  2. 如果直接从终端调用,可执行文件就会启动,但从 shell 脚本调用时则不起作用

答案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

相关内容