Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to find the directory which keeps a certain file and cd there. e.g.

find * -name hello.txt 

output: Documents/Projects/hello.txt

cd Documents/Projects

How do I pipe these commands? Thanks!

share|improve this question
what would you want to do if find locates more than one copy of hello.txt ? – Iain Sep 6 '11 at 10:44
good question! just goto the location of the first dir which holds hello.txt – OckhamsRazor Sep 6 '11 at 10:46
up vote 13 down vote accepted


cd $(dirname$(find /path -name hello.txt | head -n 1))


cd $(find /path -name hello.txt | head -n 1 | xargs dirname)

You'll need to provide a path to search, * in your above wouldn't work as the shell would expand it.

EDIT and if you have spaces in your filenames

cd $(find /home -name 'he llo.txt' -print0 -quit | xargs -0 dirname)

and if you have spaces in your directory names too

 cd "$(find /path -name 'hello.txt' -print0 -quit | xargs -0 dirname)"
share|improve this answer
dirname, not basename. – quanta Sep 6 '11 at 10:57
thanks Iain, but now i'm getting "usage: dirname path". – OckhamsRazor Sep 6 '11 at 11:21
adding quotations solves it. however, your solution does not work for directories whose names have spaces in them. do you know how that could be done? thanks! – OckhamsRazor Sep 6 '11 at 11:28
Put quotes around the subshell "$( find ...)" – Iain Sep 6 '11 at 11:39
awesome, well done! – OckhamsRazor Sep 6 '11 at 11:50

Instead of finding all and head -1, just use -quit option to make find command stop after the first hello.txt file was found:

$ cd $(dirname $(find /path -name hello.txt -print -quit))
share|improve this answer
oooh - -quit I like that – Iain Sep 6 '11 at 11:11

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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