在写shell合并脚本的时候,我们通常会使用相对路径来获取文件内容,比如:

1
2
3
4
assetsPath='.';
debugPath='../debug';
 
//然后从$assetsPath目录下开始执行shell脚本
但有的时候,我们也许需要用到绝对路径。shell怎么获取一个文件或目录的绝对路径呢?

也许你会立马想到realpath(如果你写过php的话),那么shell支持这个命令吗?看一下这里你就知道了。

1
Realpath appears to come from debian, and is not part of coreutils,Realpath appears not to be standard issue.
看来使用这个命令并不怎么靠谱,怎么办呢?经过一番查询,找到了readlink命令:

1
debugPath=`readlink -f '../debug'`;
这样就可以获得文件的绝对路径了,readlink的具体用法请自行man readlink!

(note:readlink对于softlink的处理貌似有点不符合期望,在处理softlink时,readlink拿到的是实际的文件路径,而不是softlink路径。)