Search code examples
bashcd

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


Is it possible in bash to automatically cd into a directory even without typing cd?

E.g., I'd like to be able to cd into ./whatever when just typing the following into the terminal:

./whatever

Is there a way to achieve this with bash? I know that zsh supports this.

One of my thoughts was to catch the Is a directory error thrown by bash when just typing ./whatever and subsequently cd into that directory but I couldn't find out a way to do it.


Solution

  • Yes, just enable the shell option autocd:

    shopt -s autocd
    

    From the 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.