Linux: execute a command for each directory of current directory

you are in ~/scripts and you have several subdirectories like the following image:

Image for post

You want for each directory of scripts to execute a command, which in our case the command is “git init”, the long and borring way is to cd each directory and execute the command. If you dont have many directories this borring but still feasible, if the directories where lets say 100, would be a very hard task, of course you can do some scripting but bash has some very nice one liners for such tasks


$ find . -maxdepth 1 -type d \( ! -name . \) -exec bash -c "cd '{}' && git init" \;

Executing this will produce:

Image for post

We can see that git init executed in each directory, lets explain the parameters

  • find: the find command
  • . : The dot instructs find to start searching from current directory
  • -maxdepth 1: if a directory has subdirectories dont go in!
  • -type d: we care only for directories, ignore anything else
  • \( ! -name . \): ignore current directory
  • -exec bash -c "cd '{}' && git init" \;”: for each found directory execute bash with the command we pass after the -c switch, the {} will be replaced with the found directory

I hope you found this article useful :)

Written by

DevOps engineer, loves Linux, Python, cats and Amiga computers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store