0

Is there a way to get bash to cd to a directory by default if I just enter the directory name?

Right now what I get is:

~ bemmu$ some_directory/
-bash: some_directory/: is a directory

What I want to happen is:

~ bemmu$ some_directory/
~/some_directory bemmu$ 

Tried to Google a bit but couldn't find an answer. I'm on "GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15)".

2
  • I think even if it might be implemented, as the interpreter's response to all or undefined, non-existing commands, It would go against the very rules of syntax, that's why it won't be recommended anyhow.
    – user373230
    Oct 3, 2016 at 5:56
  • 3
    Answered e.g. here (autocd option).
    – dirkt
    Oct 3, 2016 at 6:08

2 Answers 2

1

Add this to bottom of your .bashrc file

try_cd_on_error()
{
    trap trycd ERR
}
trycd() {
    trap "" ERR
    if cd $BASH_COMMAND 2>/dev/null; then
        pwd
        trap trycd ERR
        return
    fi
    trap trycd ERR
}

then start a new bash shell, and enter try_cd_on_error to set it up, then enter a directory name.

2

One of the comments points to this answer.

To enable the feature:

shopt -s autocd

(You may want to add the above line to your .bashrc.)

To disable:

shopt -u autocd
1
  • Good to know for the future, but now I'm on older bash. Looks like this is introduced in 4.0.
    – Bemmu
    Oct 4, 2016 at 0:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .