How to enter every directory in current path and execute script

find . -type d -exec bash -c 'cd "$0" && pwd' {} \;

Swap pwd for your script. And . for the root directory name, if it's not the "current" directory.

You have to wrap the exec clause in bash -c "..." because of the way -exec works. cd doesn't exist in its limited environment, but as you can see by running the above command, when you bring in bash to do the job, everything runs as predicted.

Edit: I'm not sure why 2011 Oli didn't think of -execdir but that's probably a faster solution:

find . -type d -execdir pwd \;

If you can, use find as suggested in other answers, xargs is almost always to be avoided.

But if you still want to use xargs, a possible alternative is the following:

printf '%s\0' */ | xargs -0 -L1 bash -c 'cd -- "$1" && pwd' _

Some notes:

  1. */ expands to the list of directories in the current folder, thanks to the trailing slash

  2. printf with \0 (null byte) separates the elements one for each line

  3. the option -L1 to xargs makes it to execute once for every input line and the option -0 makes it separate the input on the null byte: filenames can contain any character, the command doesn't break!

  4. bash removes the double quotes and pass it to the inline script as a single parameter, but cd should put double quotes again to interpret it as a single string; using -- makes the cd command robust against filenames that start with a hyphen

  5. to avoid the strange use of $0 as a parameter, is usual to put a first dummy argument _


You shouldn't parse ls in the first place.

You can use GNU find for that and its -execdir parameter, e.g.:

find . -type d -execdir realpath "{}" ';'

or more practical example:

find . -name .git -type d -execdir git pull -v ';'

and here is version with xargs:

find . -type d -print0 | xargs -0 -I% sh -c 'cd "%" && pwd && echo Do stuff'

For more examples, see: How to go to each directory and execute a command? at SO