温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-09-10 13:24:46 来源:亿速云 阅读:123 作者:小新 栏目:开发技术

这篇文章主要介绍了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如何获取当前正在执行脚本的绝对路径”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI