Linux – cd in bash causes cd to different directory

bashlinux

Ok, so I've been using Linux for 18 years and have never seen or heard of anything like this:

starting-forth$ ls
ch01/  ch02/  ch04/  ch05/  ch06/  text/
starting-forth$ cd ch07  # A directory I thought I might exist, but didn't
ch04
ch04$

Wat?! Ok, just to make sure:

ch04$ pwd
/home/m/learn/forth/starting-forth/ch04

My shell is bash, in a virtual terminal [LilyTerm, to be exact], in an XFCE session, on Manjaro Linux. I don't think I have made any weird customizations, and the system as a whole is fairly new (initial installation October 2014 on a new laptop).

So, anyone have any idea what could cause this?

UPDATE: One fact that didn't occur to me before (though I don't know why it would matter) is that this is taking place within a Git working directory.

UPDATE 2: Apparently this behavior occurs whenever there is an existing directory whose name is the same, except for the final character (or two characters?), as the nonexistent directory I try to cd to. For example:

[tmp]$ mkdir dxx17903
[tmp]$ cd dxx17907
dxx17903
[tmp]$ cd dxx179035
dxx17903
[dxx17903]$ cd ..
[tmp]$ cd dxx179005
bash: cd: dxx179005: No such file or directory
[tmp]$ cd dxx179
bash: cd: dxx179: No such file or directory
[tmp]$ cd dxx1790
dxx17903
[dxx17903]$ cd ..
[tmp]$ mkdir foot
[tmp]$ mkdir food
[tmp]$ cd fool
foot
[foot]$ cd ..
[tmp]$ cd football
bash: cd: football: No such file or directory
[tmp]$ cd foo
foot
[foot]$

And so on … it appears that when there is more than one directory that "matches" (in this strange and undesired way), the one you go to is the one that was created first.

Best Answer

Check

shopt cdspell

If this is set, and you cd to a directory that doesn't exist, the shell will look to see whether there's a directory with a name similar to what you typed.  (It assumes that you made a spelling mistake.)  If it finds something similar to what you typed, it assume that that's what you meant, and it is notoriously indiscriminate — if there are several names similar to what you typed (e.g., cab, cad, can, cap, car, and cat), it will pick one, seemingly at random.

Or, maybe, it's the one that appears first in the directory (which is probably the oldest one).

Related Question