是否有一个命令来检索给定相对路径的绝对路径?

例如,我想要$line包含dir ./etc/中每个文件的绝对路径

find ./ -type f | while read line; do
   echo $line
done

当前回答

你可以使用bash字符串替换任何相对路径$line:

line=$(echo ${line/#..\//`cd ..; pwd`\/})
line=$(echo ${line/#.\//`pwd`\/})
echo $line

基本的字符串前端替换遵循以下公式 ${/ #子字符串替换字符串} 在这里讨论得很好:https://www.tldp.org/LDP/abs/html/string-manipulation.html

当我们希望/是我们找到/替换的字符串的一部分时,\字符对/求反。

其他回答

在find的情况下,可能最简单的是给它搜索的绝对路径,例如:

find /etc
find `pwd`/subdir_of_current_dir/ -type f

恕我直言,最好的解决方案是在这里发布的:https://stackoverflow.com/a/3373298/9724628。

它确实需要python才能工作,但它似乎涵盖了所有或大部分边缘情况,是非常可移植的解决方案。

通过解析符号链接:

python -c "import os,sys; print(os.path.realpath(sys.argv[1]))" path/to/file

或者没有它:

python -c "import os,sys; print(os.path.abspath(sys.argv[1]))" path/to/file

类似于@ernest-a的答案,但不影响$OLDPWD或定义一个新函数,您可以触发一个子shell (cd <path>;pwd)

$ pwd
/etc/apache2
$ cd ../cups 
$ cd -
/etc/apache2
$ (cd ~/..; pwd)
/Users
$ cd -
/etc/cups

我无法找到一个解决方案,可以在Mac OS Catalina, Ubuntu 16和Centos 7之间巧妙地移植,所以我决定用python内联来做,它对我的bash脚本工作得很好。

to_abs_path() {
  python -c "import os; print os.path.abspath('$1')"
}

to_abs_path "/some_path/../secrets"

如果相对路径是一个目录路径,那么试试我的,应该是最好的:

absPath=$(pushd ../SOME_RELATIVE_PATH_TO_Directory > /dev/null && pwd && popd > /dev/null)

echo $absPath