One of the other answers came close to this:
find . -type d -exec sh -c 'cd "$0" && cmd' {} \;
(running the command only if the cd
succeeds).
Some people recommend inserting a dummy argument,
so the found directory ({}
) slides over to $1
:
find . -type d -exec sh -c 'cd "$1" && cmd' foo {} ";"
Of course, you can use any string here in place of foo
.
Common choices include -
, --
, and sh
.
This string will be used in error messages (if any), e.g.,
foo: line 0: cd: restricted_directory: Permission denied
so sh
seems to be a good choice.
\;
and ";"
are absolutely equivalent; that’s just a style preference.
The above commands execute the shell once for each directory.
This may come with some performance penalty
(especially if the command to be executed is relatively light-weight).
Alternatives include
find . -type d -exec sh -c 'for d; do (cd "$d" && cmd); done' sh {} +
which executes the shell once, but forks once for each directory, and
find . -type d -exec sh -c 'save_d=$PWD; for d; do cd "$d" && cmd; cd "$save_d"; done' sh {} +
which doesn’t spawn any subshells. If you are searching an absolute path,
as your question suggests, you can combine the above and do
find /home/test -type d -exec sh -c 'for d; do cd "$d" && cmd; done' sh {} +
which doesn’t spawn any subshells
and also doesn’t have to bother with saving the starting point.
pwd
as a proof of concept? – G-Man Says 'Reinstate Monica' May 17 '15 at 03:16pwd
is pretty special in many ways - that's what causes confusion as it is used as example command. – Volker Siegel May 17 '15 at 11:31