Shell获取当前正在执行脚本的绝对路径

1. pwd命令

我们看看使用pwd命令能否获取当前正在执行脚本的绝对路径。该命令的作用是“print name of current/working directory”,真实含义是当前工作目录,并不是正在执行脚本的目录。

xiaosi@qunar:~/company/sh$ cat pwd.sh
echo `pwd`
xiaosi@qunar:~/company/sh$ sh pwd.sh
/home/xiaosi/company/sh
xiaosi@qunar:~/company/sh$ cd ..
xiaosi@qunar:~/company$ sh sh/pwd.sh 
/home/xiaosi/company

pwd.sh脚本中只有一句:echo `pwd`。通过在不同路径下运行脚本,sh pwd.sh得到/home/xiaosi/company/sh,然而sh sh/pwd.sh 得到/home/xiaosi/company,所以说pwd命令并不能得到正在执行脚本的目录。

2. $0

$0是bash环境下的特殊变量,其真实含义是:expands to the name of the shell or shell script. this is set at shell initialization.  if bash is invoked with a file of commands, $0 is set to the name of that file. if bash is started with the -c option, then $0 is set to the first argument after the string to be executed, if one is present. otherwise, it is set to the file name used to invoke bash, as given by argument zero。

$0值与调用的方式有关:

(1)使用一个文件调用bash,那$0的值是文件的名字

xiaosi@qunar:~/company/sh$ cat pwd.sh 
echo $0
xiaosi@qunar:~/company/sh$ sh pwd.sh 
pwd.sh

(2)使用-c选项启动bash,真正执行的命令会从一个字符串中读取,字符串后面如果还有别的参数的话,使用从$0开始的特殊变量引用(跟路径无关了)

(3)除此以外,$0会被设置成调用bash的那个文件的名字(没说是绝对路径)

3. 正解

basepath=$(cd `dirname $0`; pwd)

dirname $0,取得当前执行的脚本文件的父目录

cd `dirname $0`,进入这个目录(切换当前工作目录)

pwd,显示当前工作目录(cd执行后的)

到此这篇关于shell获取当前正在执行脚本的绝对路径的文章就介绍到这了,更多相关shell获取脚本绝对路径内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐