一、shell 脚本
function trim_path()
{
local _path="${1}"
# 如果路径最后有 '/',需要去掉,否则无法获取绝对路径
while true ; do
if [[ ${_path} =~ /$ ]] ; then
_path=${_path:0:-1}
else
break
fi
done
echo "${_path}"
}
function get_abspath()
{
local _path="${1}"
# 对于相对路径,把他的绝对路径补齐
if [[ ${_path} =~ ^/ ]] ; then
_path=${_path}
else
_path="$(pwd)/${_path}"
fi
_path=$(trim_path ${_path})
while [ -h "${_path}" ] ; do
local _topath=$(ls -ld ${_path} | awk '{print $NF}')
local _frompath=$(ls -ld ${_path} | awk '{print $(NF-2)}')
if [[ ${_topath} =~ ^/ ]] ; then
_path=${_topath}
else
_path="$(dirname ${_frompath})/${_topath}"
fi
_path=$(trim_path ${_path})
done
echo ${_path}
}
get_abspath ${1}
二、演示
2.1 当前目录中的文件列表
$ ls -l
-rwxr-xr-x 1 root root 1211 Dec 8 15:46 get-real-file-path.sh
lrwxrwxrwx 1 root root 8 Aug 5 21:05 link-dir1 -> real-dir
lrwxrwxrwx 1 root root 9 Aug 5 21:05 link-dir2 -> real-dir/
lrwxrwxrwx 1 root root 9 Dec 8 15:15 link-dir3 -> link-dir1
lrwxrwxrwx 1 root root 13 Aug 5 21:05 link-file.txt -> real-file.txt
drwxr-xr-x 2 root root 31 Dec 8 15:14 real-dir
-rw-r--r-- 1 root root 0 Aug 5 21:04 real-file.txt
其中 real-file.txt 、real-dir和 get-real-file-path.sh 不是链接文件,其余几个文件都是链接文件。
2.1 获取链接文件的真实文件路径
$ ./get-real-file-path.sh link-dir1
/root/workspace/practice/practice/shell/file/real-dir
$ ./get-real-file-path.sh link-dir1/
/root/workspace/practice/practice/shell/file/real-dir
$ ./get-real-file-path.sh link-file.txt
/root/workspace/practice/practice/shell/file/real-file.txt

该博客介绍了两个Shell函数,trim_path和get_abspath,用于处理和获取文件的绝对路径,特别针对链接文件。在示例中,脚本成功地揭示了不同链接文件指向的真实目录和文件。内容涵盖了文件系统的软链接处理和绝对路径的计算,对于理解和操作Linux文件系统有一定帮助。

2813

被折叠的 条评论
为什么被折叠?



