Linux 如何在bash脚本中将路径名中的“..”转换为绝对名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6643853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:02:36  来源:igfitidea点击:

How to convert ".." in path names to absolute name in a bash script?

linuxbashunix

提问by Nohsib

How to convert the ..in the path names to absolute path names in a bash script. That is, if I have a path /home/nohsib/dvc/../bop, I want this to be changed to the path without dots in it, in this case /home/nohsib/bop

如何..在 bash 脚本中将路径名中的转换为绝对路径名。也就是说,如果我有一个 path /home/nohsib/dvc/../bop,我希望将其更改为没有点的路径,在这种情况下/home/nohsib/bop

How can I do that?

我怎样才能做到这一点?

采纳答案by Martin

What you're looking for is readlink:

你要找的是readlink

absolute_path=$(readlink -m /home/nohsib/dvc/../bop)

Please note:You need to use GNU's readlinkimplementation which offers the "-m" option. BSD's readlinkfor example does not.

请注意:您需要使用readlink提供“-m”选项的GNU实现。readlink例如,BSD就没有。

回答by dimba

Try:

尝试:

ABSOLUTE_PATH=$(cd /home/nohsib/dvc/../bop; pwd)

回答by Fredrik Pihl

Use

echo Absolute path: $(cd ; pwd)

回答by ennuikiller

Try this (assuming your relative path is stored in the variable $rel_path):

试试这个(假设你的相对路径存储在变量 $rel_path 中):

echo "`cd $rel_path; pwd`"

回答by portforwardpodcast

Just an additional note, if your current path is under a symlink, you can resolve the true path with this:

补充说明一下,如果您当前的路径在符号链接下,您可以使用以下方法解析真实路径:

pwd -P

To solve your specific problem, this will issue a cdcommand to change directory to the path without the '..' in it. Note you will be in the same folder, just with the correct path:

为了解决您的特定问题,这将发出一个cd命令,将目录更改为不带“..”的路径。请注意,您将位于同一个文件夹中,只是使用正确的路径:

cd `pwd -P`

回答by konsolebox

As an alternative to GNU's readlink and realpath, I had created functions as well that would run in scripts independent of external commands like pwd and stuffs.

作为 GNU 的 readlink 和 realpath 的替代方案,我还创建了可以在独立于外部命令(如 pwd 和 stuffs)的脚本中运行的函数。

http://www.linuxquestions.org/questions/blog/konsolebox-210384/getting-absolute-paths-of-unix-directories-and-filenames-in-shell-scripts-3956/

http://www.linuxquestions.org/questions/blog/konsolebox-210384/getting-absolute-paths-of-unix-directories-and-filenames-in-shell-scripts-3956/

One of those is this one. It will save the absolute path to $__. I used read there to be safe from pathname expansion.

其中之一就是这个。它将保存到 $__ 的绝对路径。我使用 read 来避免路径名扩展。

function getabspath {
    local -a T1 T2
    local -i I=0
    local IFS=/ A

    case "" in
    /*)
        read -r -a T1 <<< ""
        ;;
    *)
        read -r -a T1 <<< "/$PWD/"
        ;;
    esac

    T2=()

    for A in "${T1[@]}"; do
        case "$A" in
        ..)
            [[ I -ne 0 ]] && unset T2\[--I\]
            continue
            ;;
        .|'')
            continue
            ;;
        esac

        T2[I++]=$A
    done

    case "" in
    */)
        [[ I -ne 0 ]] && __="/${T2[*]}/" || __=/
        ;;
    *)
        [[ I -ne 0 ]] && __="/${T2[*]}" || __=/.
        ;;
    esac
}

回答by cyril F.

one good solution under a shell would be :

shell下的一个很好的解决方案是:

readlink -ev mypathname

It prints out the full path name with dots resolved.

它打印出带有解析点的完整路径名。

回答by Gino

One issue with using :

使用的一个问题:

ABSOLUTE_PATH=$(cd ${possibleDirectory}; pwd)

ABSOLUTE_PATH=$(cd ${possibleDirectory}; pwd)

is that if ${possibleDirectory} doesn't exist, ABSOLUTE_PATH will then be set to the current directory. Which is probably NOT what you want or expect.

是如果 ${possibleDirectory} 不存在,则 ABSOLUTE_PATH 将被设置为当前目录。这可能不是您想要或期望的。

I think using this version may be more desirable in general:

我认为通常使用此版本可能更可取:

ABSOLUTE_PATH=$(cd ${possibleDirectory} && pwd)

ABSOLUTE_PATH=$(cd ${possibleDirectory} && pwd)

If ${possibleDirectory} does not exist or is not accessible, due to missing directory access permissions, ABSOLUTE_PATH will contain the empty string.

如果 ${possibleDirectory} 不存在或不可访问,由于缺少目录访问权限,ABSOLUTE_PATH 将包含空字符串。

The advantage of this is that you can then test for the empty string or let it fail naturally, depending on the circumstances. Defaulting to the current directory in the case of a failed 'cd' command may lead to very unexpected and possibly disastrous results (e.g. rm -rf "$ABSOLUTE_PATH" )

这样做的好处是,您可以根据情况测试空字符串或让它自然失败。在 'cd' 命令失败的情况下默认为当前目录可能会导致非常意外且可能是灾难性的结果(例如 rm -rf "$ABSOLUTE_PATH" )

回答by Craig McQueen

If you want to do it without following any symlinks, then try using realpathwith option -s:

如果您想在不遵循任何符号链接的情况下执行此操作,请尝试使用realpathwith option -s

$ realpath -s /home/nohsib/dvc/../bop
/home/nohsib/bop

Note that with realpath, normally all but the last component must exist. So for the above to work, the following must all be present in the file system:

请注意realpath,通常除了最后一个组件之外的所有组件都必须存在。因此,要使上述工作正常进行,文件系统中必须存在以下所有内容:

/home
/home/nohsib
/home/nohsib/dvc

But you can bypass that requirement using the -moption.

但是您可以使用该-m选项绕过该要求。

$ realpath -sm /home/nohsib/dvc/../bop
/home/nohsib/bop

(Note realpathis not available on all systems, especially older non-Debian systems. For those working on embedded Linux, unfortunately Busybox realpathdoesn't support the -sor -mswitches.)

(注意realpath并非在所有系统上都可用,尤其是较旧的非 Debian 系统。对于那些在嵌入式 Linux 上工作的人,不幸的是 Busyboxrealpath不支持-s-m开关。)

回答by G. C.

Relative paths must be converted into absolute, it is NOT required to exist!

相对路径必须转换成绝对路径,不需要存在!

Neither symlinks should be resolved.

两个符号链接都不应该被解析。

Try this one-line python solution:

试试这个单行 python 解决方案:

abs_path=$(python -c "import os; print(os.path.abspath(\"$rel_path\"))")  

in your example:

在你的例子中:

python -c "import os; print(os.path.abspath(\"/home/nohsib/dvc/../bop\"))"  

returns /home/nohsib/bop

返回 /home/nohsib/bop