How to use `find -exec` to execute command in directory of found file (not current directory)

find

Let's say I'm in a directory which has some subdirectories, dir1, dir2, and dir3. Each of these directories have a file foo and I would like to execute the same command on each foo in each of the directories and have that command executed from inside that directory.

If I were to do it "by hand", it would look something like this:

cd dir1
(execute on foo)
cd ../dir2
(execute on foo)
cd ../dir3
(execute on foo)

It is imperative that the command be executed from each of the directories. foo is a batch scheduling script (for HTCondor, if you care to know) and must be executed from each subdirectory so that the output of the runs started by the scheduling scripts will end up in each subdirectory.

The question "Find a file and execute a command in the file's directory", as far as I can tell, does not answer my question. The first answer to that question is more of a workaround which will not work in my case, and the second answer does not have enough of an explanation for me to know how to use it.

Best Answer

Assuming your find supports it, use the -execdir option instead of -exec

find * -name 'foo' -execdir pwd \;

If it doesn't, please provide details of your platform and/or distribution (as appropriate).

Related Question