栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

shell获取当前脚本的绝对路径

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

shell获取当前脚本的绝对路径

文章目录
  • 1. 功能说明
  • 2. 相关shell命令
    • 2.1 dirname
    • 2.2 pwd
    • 2.3 readlink
  • 3. 最终实现

1. 功能说明

通过shell脚本启动服务时,往往需要获取到当前脚本的绝对路径,再依据该绝对路径获取一些配置文件、静态库等的路径,为此,在shell脚本中拿到该脚本的绝对路径是很有用的。

2. 相关shell命令 2.1 dirname

返回文件目录名:

$ dirname path

例如:

$ dirname /a/b/c # 或者 $ dirname /a/b/c/
/a/b
$ dirname a/b/c  # 或者 $ dirname a/b/c/
a/b
$ dirname a  # 或者 $ dirname a/
.
$ dirname /  # 或者 $ dirname //
/
2.2 pwd

print working directory:

$ pwd
2.3 readlink

打印解析后的符号链接(symbol link)。

SOURCE=$(readlink "$SOURCE")
3. 最终实现
#!/usr/bin/env bash

SOURCE=$0 # $0 is the shell name, maybe absolute path, relative path or symbolic link
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  script_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$script_DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
script_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"  # script absolute path
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/458176.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号