Bash cd to a directory by just entering its name

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

Bemmu

Posted 2016-10-03T05:23:19.490

Reputation: 808

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. – None – 2016-10-03T05:56:22.563

3

Answered e.g. here (autocd option).

– dirkt – 2016-10-03T06:08:25.913

Answers

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.

strobelight

Posted 2016-10-03T05:23:19.490

Reputation: 473

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

Kamil Maciorowski

Posted 2016-10-03T05:23:19.490

Reputation: 38 429

Good to know for the future, but now I'm on older bash. Looks like this is introduced in 4.0. – Bemmu – 2016-10-04T00:32:24.593