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

复制代码代码如下:

[root@dabu.info ]#basename /root/aaa/bbb/dabu.txt

显示:

复制代码代码如下:

dabu.txt #获取路径的文件名

shell脚本中如何获得脚本文件所在路径?

方法一:

复制代码代码如下:

[root@dabu.info ]#dir=$(cd "$(dirname "$0")"; pwd)

[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

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'"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值