Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@llekn
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save llekn/6b043594641c2e8b4304 to your computer and use it in GitHub Desktop.
Save llekn/6b043594641c2e8b4304 to your computer and use it in GitHub Desktop.
Python script to execute a shell command on every sub-folder of current folder
#!/usr/bin/env python3
'''Receives a command as argument and executes it on
every sub-folder of current folder.
Useful for commands that should be run multiple times,
like doing a git fetch on a bunch of repos.
Usage: ./for-each-dir.py "command"
Example: ./for-each-dir.py "git fetch"
'''
import os
from subprocess import call
def execute_command(command):
for folder in os.listdir():
try:
os.chdir(folder)
print("\nTrying", folder + '/' + command)
retcode = call(command, shell=True)
os.chdir('..')
except NotADirectoryError:
pass
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('command', help='shell command to be executed on each folder')
args = parser.parse_args()
execute_command(args.command)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment