“ / path / file / ..”如何与POSIX兼容?

我想将当前目录更改为Shell脚本更改为包含特定常规文件的目录。我发现以下技巧在mkshbusybox sh中有效:

path=/path/to/regular/file
cd $path/.. 

但在GNU Bash中不是:

bash: cd: /path/to/regular/file/..: Not a directory

此技巧是否与posix不兼容,或者Bash过于too腐?

iCMS 回答:“ / path / file / ..”如何与POSIX兼容?

该标准的最新版本不允许这样做。 POSIX.1-2017 cd spec.说,如果点号前面的路径名组件不是目录,则cd应认为是错误。

来自cd § DESCRIPTION - step 8.b

b. For each dot-dot component,if there is a preceding component and
   it is neither root nor dot-dot,then:

    i. If the preceding component does not refer (in the context of
       pathname resolution with symbolic links followed) to a
       directory,then the cd utility shall display an appropriate
       error message and no further steps shall be taken.

使用cd选项调用-P时,将省略此步骤;但是如果路径名称组件之一命名既不是目录也不是目录的符号链接的现有文件,则chdir()失败。

此外,允许 trick 也允许cd中的行为不一致。例如,在包含名为bar常规文件和包含另一个目录的名为foo目录的目录中运行时, strong>名为bar,下面的两个命令在shell中执行不同的操作,其中cd忽略点号之前的非目录组件,尽管CDPATH包含空字符串(即当前工作目录)。

CDPATH= cd bar/..
CDPATH=:foo cd bar/..

下面的抄本清楚地显示了不合格和合格实施之间的区别。

$ tree -F
.
├── bar
└── foo/
    └── bar/

2 directories,1 file
$ ash
$ CDPATH= cd bar/..
$ pwd
/home/oguz
$ CDPATH=:foo cd bar/..
/home/oguz/foo
$ bash
$ CDPATH= cd bar/..
bash: cd: bar/..: Not a directory
$ CDPATH=:foo cd bar/..
/home/oguz/foo

boshgwshksh93u+myash是其他主动维护的shell,它们实现与bash相同的行为。

本文链接:https://www.f2er.com/2138115.html

大家都在问