当前位置: 移动技术网 > 科技>操作系统>Linux > Linux系统中获取路径的文件名的方法

Linux系统中获取路径的文件名的方法

2018年07月16日  | 移动技术网科技  | 我要评论

辽宁抚顺新闻,培养选拔年轻干部,三台新闻网


复制代码
代码如下:
[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'"

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网