19

I'm searching for a config folder, and trying to change to that directory:

find . -name "config" -exec cd {} \;

There is one match, ./my-applications/config, but after I try this it says:

find: `cd': No such file or directory

What am I doing wrong?

cwd
  • 53,018
  • 53
  • 161
  • 198

3 Answers3

23

The command cd is a shell built-in, not found in /bin or /usr/bin.

Of course, you can't change directory to a file and your search doesn't limit itself to directories. And the cd command would only affect the executed command, not the parent shell that executes the find command.

Use:

cd $(find . -name config -type d | sed 1q)

Note that if your directory is not found, you'll be back in your home directory when the command completes. (The sed 1q ensures you only pass one directory name to cd; the Korn shell cd takes two values on the command and does something fairly sensible, but Bash ignores the extras.)

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    Some OSes like Solaris do have a cd in /usr/bin but of course that doesn't change the fact they can't change the current shell directory. – jlliagre Jun 14 '11 at 05:27
  • excellent. i didn't realize that cd was a shell built in. that explains it! – cwd Jun 14 '11 at 16:08
  • 4
    If you need the _cd_ and another command, you can always use `sh -c`, for example `find . -name "config" -type d -exec sh -c "cd {}; git pull" \;` – DiegoG Jan 19 '15 at 11:07
4

In case you have more than one config directory:

select config in $(find . -name config -type d)
do
  cd $config
  break
done
jlliagre
  • 29,783
  • 6
  • 61
  • 72
  • i know this is old, but `select` should be `for` ? – Roger Oct 13 '21 at 12:14
  • @Roger I believe `select` is better than `for` here. If there is more than one `config` directory, the user can chose which one to `cd` in while with the accepted answer, the first one found is used, which is quite an arbitrary choice. – jlliagre Oct 13 '21 at 12:21
  • Maybe it’s bash? Doesn’t seem to work in sh. – Roger Oct 13 '21 at 13:06
  • @Roger Are you running an ancient Bourne shell ? How does it fail ? – jlliagre Oct 13 '21 at 13:28
2

find runs -exec programs as subprocesses and subprocesses cannot affect their parent process. So, it cannot be done. You may want to try

cd `find . -name "config"`
lhf
  • 70,581
  • 9
  • 108
  • 149