Ask Ubuntu is a question and answer site for Ubuntu users and developers. 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 use find to search for files in a directory or its subdirectories. find . -iname '*.csv', and it gives me the following output


Now, I want to check in a script whether the file t1.csv is in the current folder or in one of the subdirectories. If it's in a subdirectory, my script should descend to that directory. How can I do that?

share|improve this question

To check only for t1.csv, you can use:

find . -name 't1.csv' 

Now, to go in the first directory where t1.csv file is found, you can use:

cd $(dirname $(find . -name 't1.csv' 2>/dev/null | head -1)  2>/dev/null)

enter image description here

share|improve this answer
Thanks. But i am actually trying to compress all csv files into the same folder by going inside each folder. – Ubuntuser Sep 5 '13 at 13:36
@Ubuntuser And where you said something about this in your question? If you don't see clear, the question is: how to check whether a file is in current directory or subdirectory and if its in a subdirectory, my script should descend to that directory – Radu Rădeanu Sep 5 '13 at 13:38
@Ubuntuser If you have another question, please use Ask Ubuntu button. – Radu Rădeanu Sep 5 '13 at 13:41
I have asked the question…. See if you can answer it there :) – Ubuntuser Sep 6 '13 at 3:25
If you mean that directory won't be changed /after/ script execution, this is right. The script is runing in a subshell, and cannot change the parent shell working directory. Replace pwd with comand you want to run inside new directory or source script this way:… – sorgel Sep 6 '13 at 5:51

There's a pretty comprehensive discussion on it here:

... see also the grep man pages of course

Not sure about the 2nd part of your question though, but hope that sends you in the right direction.

share|improve this answer
if [ -f t1.csv ]
    echo "File is in target dir"
    cd `dirname $(find . -iname 't1.csv')`
share|improve this answer
I dont think it helps. you see, find command gives the path. So if i do an if statement on the file, it will always find it. I need to check if this file is present in the current directory. – Ubuntuser Sep 6 '13 at 4:45
Yes it does: all you need to do extra is check if it has more than 1 backslash ;) (./111/111 versus ./1111) – Rinzwind Sep 6 '13 at 5:28
Rinzewind, please tell me more about why more then 1 backslash is needed? – sorgel Sep 6 '13 at 6:03
No, find do not test where the command [ -f t1.csv ] does, as can be seen in the code. – MUY Belgium Mar 10 '14 at 14:03

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.