Linux系统中获取路径的文件名的方法
程序员文章站
2023-11-02 22:05:16
这篇文章主要介绍了Linux系统中获取路径的文件名的方法,文中总结出了两条,需要的朋友可以参考下... 15-06-26...
复制代码
代码如下:[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 )"
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'"
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'"
上一篇: 手工建站与自助建站的区别有哪些?