Get the App
SLTechnology News&Howtos  ›  Servers  › 

When you call a shell script, get the current directory of the script

Shulou Source: shulou.com Published: 2022-06-02 14:03:42 10月27日 Update

To write shell scripts, you generally need to take the current directory of the script as the working directory. How to get the directory of the current script?

How to get the directory where the script is located in the execution script is divided into two cases:

If the script is executed under the current path of the script, then pwd directly obtains the absolute path. If the script is called from another directory, cd to the directory where the script is located first, and then obtain the absolute path where the script is located.

Here are two ways:

The first is slightly more cumbersome: if [ "` dirname "$0" `" = "" ]|| [ "` dirname "$0" `" = ". " ] ; then CURRENT_PATH="`pwd`"else cd ` dirname "$0" ` CURRENT_PATH="`pwd`" cd - > /dev/null 2>&1 #Return to previous directory fi

The second method:

if [ `echo $0 | grep -c "/"` -gt 0 ];then

cd ${0%/*}

fi

CURRENT_DIR="$(pwd)"

The third method:

RUN_PATH=$(cd $(dirname $0); pwd)

Recommend the third writing.

Tags: Script directory location method path situation tedious writing work recommendation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Redmi macOS Microsoft vpn