I have multiple project directories project-one, project-two, different-project. I want to run ./gradlew clean build within all these directories that begin with project-. Can I use xargs to do that? How can I do that?


Since you're tagging with zsh:

for dir (project-*/gradlew(N*:h)) (cd $dir && ./gradlew clean build)

That looks for the executable (*) gradlew files in subdirs of the current working directory whose name start with project- (would also consider symlinks to directories there), takes their head to result in the directories themselves, and for each dir, start a subshell (...) inside which we change the current working directory to that dir run ./gradlew clean build if cd was successful.

Doing it with xargs would be painful. One reason you may want to do it would be if your xargs was the one from the GNU project and you wanted to run a few gradlews in parallel.

For instance.

xargs -r0 -P4 -n1 -a <(print -rNC1 project-*/gradlew(N*:h)) \
  sh -c 'cd "$1" && exec ./gradlew clean build' sh

would run up to 4 sh in Parallel, each of them taking 1 of those matching dirs, cding into it and running ./gradlew clean build.

  • Thanks for explaining the individual substeps! Does the syntax with the parens after gradlew have a name? I'd like to read up on that. Sep 15 '20 at 21:47
  • Ah, I think I got it. It's a glob modifier and the N prevents unintuitive behaviour on empty directories. Sep 15 '20 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.