When you call a shell script, get the current directory of the script
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.