shell获取脚本绝对路径

凉白开 Shell1 17,4222字数 442阅读1分28秒阅读模式

使用pwd 命令获取的是执行该命令的当前工作目录,当在其他目录调用一个脚本时会发现脚本中使用的pwd命令获取的结果不是脚本所在的绝对

一段代码获取

 文章源自运维生存时间-https://www.ttlsa.com/shell/shell-get-scripts-path/

 base_dir=$(cd "$(dirname "$0")";pwd)

 文章源自运维生存时间-https://www.ttlsa.com/shell/shell-get-scripts-path/

大脚本获取

#!/bin/sh
 this_dir=`pwd`
 echo "$this_dir ,this is pwd"
 echo "$0 ,this is \$0"
 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

 文章源自运维生存时间-https://www.ttlsa.com/shell/shell-get-scripts-path/

转自:http://www.zhengdazhi.com/?p=139文章源自运维生存时间-https://www.ttlsa.com/shell/shell-get-scripts-path/ 文章源自运维生存时间-https://www.ttlsa.com/shell/shell-get-scripts-path/

weinxin
我的微信
微信公众号
扫一扫关注运维生存时间公众号,获取最新技术文章~
凉白开
  • 本文由 发表于 04/11/2014 16:54:23
  • 转载请务必保留本文链接:https://www.ttlsa.com/shell/shell-get-scripts-path/
  • Linux
  • shell
  • 脚本绝对路径
  • 获取shell路径
评论  1  访客  1
    • 潇湘居士
      潇湘居士 9

      一般使用:
      cd — "$(dirname — "$0")"

    评论已关闭!