欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

linux 在shell脚本中获取该脚本的所在绝对路径 博客分类: unixlinux命令 linux获取脚本绝对路径绝对路径shellabsolute 

程序员文章站 2024-02-24 19:16:40
...

脚本名:a.sh

位置:/tmp/whuang/study/java

脚本内容:

 

#!/bin/sh
this_dir=`pwd`
dirname $0|grep "^/" >/dev/null
if [ $? -eq 0 ];then
                this_dir=`dirname $0`
else
        dirname $0|grep "^\." >/dev/null
        retval=$?
        if [ $retval -eq 0 ];then
                        this_dir=`dirname $0|sed "s#^.#$this_dir#"`
        else
                   this_dir=`dirname $0|sed "s#^#$this_dir/#"`
        fi
fi
echo $this_dir

 

----------------------------------------------

功能:获取脚本的绝对路径。

测试:

 

[root@ppc40 java]# pwd

/tmp/whuang/study/java

[root@ppc40 java]# sh a.sh

/tmp/whuang/study/java

[root@ppc40 java]# cd ..

[root@ppc40 study]# sh java/a.sh

/tmp/whuang/study/java

[root@ppc40 study]# sh ./java/a.sh

/tmp/whuang/study/java