linux shell 文件如何知道自身位置?

2015 年 1 月 13 日
 otmb

a.sh

path=xxx

经常使用source xxpath/a.sh 调用a.sh
在a.sh中如何获取自身所在文件夹路径呢?

3993 次点击
所在节点    程序员
20 条回复
eamars
2015 年 1 月 13 日
cd "$(dirname "$0")"
gamecreating
2015 年 1 月 13 日
pwd
otmb
2015 年 1 月 13 日
@eamars 通过source a.sh,这种方法不能获取文件所在的路径
eamars
2015 年 1 月 13 日
bellchu
2015 年 1 月 13 日
realpath
otmb
2015 年 1 月 13 日
@bellchu 不行
bellchu
2015 年 1 月 13 日
@otmb readlink呢? 有的系统可能没有realpath命令
otmb
2015 年 1 月 13 日
@bellchu 通过source调用脚本,不行的
bellchu
2015 年 1 月 13 日
@otmb

SCRIPTPATH=`realpath`
otmb
2015 年 1 月 13 日
@eamars bash中好像$0无论何种情况都等于$_的?
otmb
2015 年 1 月 13 日
@bellchu
source xxx/a.sh
你所得到的path是当前目录,而不是a.sh所在路径
Beebird
2015 年 1 月 13 日
#!/bin/env bash
...
LOCATION=$(pwd)
#echo $LOCATION
...
otmb
2015 年 1 月 13 日
@Beebird source 不行的
lululau
2015 年 1 月 13 日
zsh 测试通过:

➜ cat test.sh
dir=`(cd "$(dirname "$0")"; pwd)`

➜ 2.2.0 ~/tmp
➜ source test.sh

➜ 2.2.0 ~/tmp
➜ echo $dir
/Users/liuxiang/tmp
otmb
2015 年 1 月 13 日
@lululau 为啥不用bash?
lululau
2015 年 1 月 13 日
@otmb zsh 功能比 bash 丰富很多
lululau
2015 年 1 月 13 日
@otmb bash 测试也没问题啊
Beebird
2015 年 1 月 13 日
@otmb 试了可以啊,不论是source还是直接运行。

cat testpwd.sh

#!/bin/env bash

LOCATION=$(pwd)
echo $LOCATION


$ source testpwd.sh
/home/lzhao/tmp
HowardMei
2015 年 1 月 13 日
sh和bash下面source和直接执行需要的判断参数不同,从"$_" "$0" "$BASH_SOURCE"三个里面找,如果是curl或cat script.sh | bash方式,
这三个都没用,参考:
https://github.com/HowardMei/shbin/blob/master/shbin/shsrc
KentY
2015 年 1 月 13 日
我是这么弄的,也判断link的情况,readlink读真实dir

https://github.com/sk1418/passwdmanager/blob/master/start.sh

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://v2ex.ih06.com/t/161742

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX