我想将当前目录更改为Shell脚本更改为包含特定常规文件的目录。我发现以下技巧在mksh
和busybox sh
中有效:
path=/path/to/regular/file
cd $path/..
但在GNU Bash中不是:
bash: cd: /path/to/regular/file/..: Not a directory
此技巧是否与posix不兼容,或者Bash过于too腐?
我想将当前目录更改为Shell脚本更改为包含特定常规文件的目录。我发现以下技巧在mksh
和busybox sh
中有效:
path=/path/to/regular/file
cd $path/..
但在GNU Bash中不是:
bash: cd: /path/to/regular/file/..: Not a directory
此技巧是否与posix不兼容,或者Bash过于too腐?
该标准的最新版本不允许这样做。 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