辽宁抚顺新闻,培养选拔年轻干部,三台新闻网
[root@dabu.info ]#basename /root/aaa/bbb/dabu.txt
显示:
dabu.txt #获取路径的文件名
shell脚本中如何获得脚本文件所在路径?
方法一:
[root@dabu.info ]#dir=$(cd "$(dirname "$0")"; pwd)</p>
<p>[root@dabu.info ]#echo $dir
但是像这种dirname "$0"这种写法,在遇到source命令时会得到错误的结果。
方法二:
[root@dabu.info ]#echo "$( cd "$( dirname "${bash_source[0]}" )" && pwd )"
上面一行命令可以获得脚本的绝对轮径,无论你在何处调用这个脚本。
但是如果含有软链接,就无法使用了。所以,我们为了能正确解析指向脚本的软链接,可以使用下面的多行命令:
source="${bash_source[0]}"
while [ -h "$source" ]; do # resolve $source until the file is no longer a symlink
dir="$( cd -p "$( dirname "$source" )" && pwd )"
source="$(readlink "$source")"
[[ $source != /* ]] && source="$dir/$source" # if $source was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
dir="$( cd -p "$( dirname "$source" )" && pwd )"
也可与source,bash -c命令使用
但是,如果你在脚本中使用先cd切换到其他目录,在运行时上面的命令片段时,则上面的命令不能等到正确的结果。可以参考关于$cdpath 陷阱的文章。想理解它如何其作用的,可以运行下面的代码:
#!/bin/bash</p>
<p> source="${bash_source[0]}"
while [ -h "$source" ]; do # resolve $source until the file is no longer a symlink
target="$(readlink "$source")"
if [[ $source == /* ]]; then
echo "source '$source' is an absolute symlink to '$target'"
source="$target"
else
dir="$( dirname "$source" )"
echo "source '$source' is a relative symlink to '$target' (relative to '$dir')"
source="$dir/$target" # if $source was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
echo "source is '$source'"
rdir="$( dirname "$source" )"
dir="$( cd -p "$( dirname "$source" )" && pwd )"
if [ "$dir" != "$rdir" ]; then
echo "dir '$rdir' resolves to '$dir'"
fi
echo "dir is '$dir'"
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!!
点击进行留言回复
相关文章:
-
-
-
应用系统分布式构建运维
应用系统分布式构建运维 1+x初级,项目四 部署主从数据库 基础环境安装 准备两台主机 修改主机名 # hostnamectl set-hos...
[阅读全文]
-
-
Linux环境变量
在bash shell中,环境变量分为两类: 全局变量 局部变量 全局环境变量 全局环境变量对于shell会话和所有生成的子shell都是可见的。例如 ...
[阅读全文]
-
-
-
初步进入Linux世界
初步进入Linux世界 一、Linux目录介绍 1.树型目录结构 Linux文件系统采用了多级目录的树型层次结构管理文件。树型结构的最上层是根目录,用/...
[阅读全文]
-
Linux常用命令(详细)
Linux常用命令 一、控制台相关命令 控制台命令就是指通过字符界面输入的可以操作系统的命令。我们现在要了解的是基于Linux操作系统的基本控制台命令。...
[阅读全文]
-
-
网友评论