How to enter every directory in current path and execute script
I want to enter every directory retuned by ls
command and execute script.
I tried this (and many other things), but it just does not work
ls | awk '{print $1" && pwd"}' | xargs cd
How to do it without for loop?
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:
*/
expands to the list of directories in the current folder, thanks to the trailing slashprintf
with\0
(null byte) separates the elements one for each linethe option
-L1
toxargs
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!bash
removes the double quotes and pass it to the inline script as a single parameter, butcd
should put double quotes again to interpret it as a single string; using--
makes thecd
command robust against filenames that start with a hyphento 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