linux获取shell脚本所在绝对路径操作介绍

10/21/2015来源:网络管理人气:2382

  脚本名: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

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

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

  测试:

  [[email protected] java]# pwd

  /tmp/whuang/study/java

  [[email protected] java]# sh a.sh

  /tmp/whuang/study/java

  [[email protected] java]# cd ..

  [[email protected] study]# sh java/a.sh

  /tmp/whuang/study/java

  [[email protected] study]# sh ./java/a.sh

  /tmp/whuang/study/java