在脚本中将带有“..”元素的路径转换为绝对路径?

时间:2014-05-23 18:34:33

标签: bash shell path sh relative-path

因此,当编码bash / sh脚本时,我在变量中获得了一个具有以下内容的路径:

$SOMEPATH=/usr/lib64/pkgconfig/../..

如何将$ SOMEVAR转换为将“..”文件夹转换为此值的完整绝对路径?:

$SOMEFULLPATH=/usr

由于

2 个答案:

答案 0 :(得分:4)

您可以使用readlink

readlink -f "$SOMEPATH"
   -f, --canonicalize
          canonicalize  by  following  every symlink in every component of
          the given name recursively; all  but  the  last  component  must
          exist

   -m, --canonicalize-missing
          canonicalize by following every symlink in  every  component  of
          the  given  name recursively, without requirements on components
          existence

答案 1 :(得分:1)

与@devnull的答案类似,我建议readlink,但-m选项不要求文件路径的任何部分已经存在,这更灵活。
readlink -m $SOMEFULLPATH