假设没有指定命令且第一个参数是目录时使用 cd

Assume cd when no command is specified and the first argument is a directory

是否可以在 bash 中自动 cd 进入目录,甚至无需键入 cd

例如,我希望能够 cd 进入 ./whatever 只需在终端中输入以下内容:

./whatever

有没有办法用 bash 实现这个?我知道 zsh 支持这个。

我的一个想法是捕捉 Is a directory 错误,当输入 ./whatever 然后 cd 到那个目录时 bash 抛出,但我找不到解决方法。

是的,只需启用 shell 选项 autocd:

shopt -s autocd

来自Bash Reference Manual

autocd

If set, a command name that is the name of a directory is executed as if it were the argument to the cd command. This option is only used by interactive shells.