0

Suppose I have two different directories with the same folder names:

/usr/myDir/ and /home/myDir/

If I run a command such as:

cd $(find / -type d -name myDir)

it navigates to /usr/myDir. Why is that? Where does the find command look first when it comes to special instances like this?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

2 Answers2

3

There's two issues; how cd behaves, which is easy to test via:

bash-4.1$ mkdir first second
bash-4.1$ cd first second
bash-4.1$ pwd
/home/jdoe/first
bash-4.1$ 

So cd for this shell is going to the first item found. Second, find itself may or may not be doing any sorting of the results, and for directories (probably) only has a -d or "find first by depth" option, which would return /some/deeper/dir before /some or /. Thus, you're left with what the system call returns, getdents(2) from a quick strace of find on Linux. These entries should not ever be assumed to be sorted in a particular order (unless something like ls sorts them for you):

bash-4.1$ mkdir c ; sleep 5
bash-4.1$ mkdir b ; sleep 5
bash-4.1$ mkdir a ; sleep 5
bash-4.1$ find .
.
./b
./c
./a

If in doubt, you'll need to enforce some sort of sorting on the results, as by default, find will find whatever the underlying system call for the filesystem returns first.

thrig
  • 34,938
1

find traverses files in whatever order the filesystem returns. This order is not predictable; creating, removing or renaming a file can change the order of other files in the same directory.

It's a toss-up whether find / -type d -name myDir returns /usr/myDir or /home/myDir first, and it could change at any time. (In this specific example, it probably won't change often, because it's rare to write to the root directory, but in general don't count on it.)

In some shells (including bash), the cd command ignores all but its first arguments, so your command silently changes the working directory to whatever find returns first. (Your command also wouldn't work for a path containing spaces.) In other shells (such as ksh and zsh), you'd get an error message.