Skip to main content
4 of 5
Respond to criticism
Chris Davies
  • 128.5k
  • 16
  • 179
  • 325

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

find . -type f -name 'foo' -execdir pwd \; 

This will change into each directory in turn, and if there's a foo file present there it will run pwd.

NB You cannot repurpose this solution for running commands inside directories named foo. For that you'd need to revert to a simple -exec sh -c '...' approach, iterating across the args supplied to sh and using cd for each in turn:

find . -type d -name 'foodir' -exec sh -c ' for d in "$@"; do ( cd "$d" || exit; pwd ); done ' _ {} + 
Chris Davies
  • 128.5k
  • 16
  • 179
  • 325