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)".

  • 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 '16 at 5:56
  • 3
    Answered e.g. here (autocd option). – dirkt Oct 3 '16 at 6:08
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
  • Good to know for the future, but now I'm on older bash. Looks like this is introduced in 4.0. – Bemmu Oct 4 '16 at 0:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.