Skip to content

Instantly share code, notes, and snippets.

@arunvijayshankar
Last active December 24, 2022 23:38
Show Gist options
  • Save arunvijayshankar/a61fb0cd840f86e5f9ad4d4132497bf9 to your computer and use it in GitHub Desktop.
Save arunvijayshankar/a61fb0cd840f86e5f9ad4d4132497bf9 to your computer and use it in GitHub Desktop.
Run a linux command recursively in every subdirectory including current working directory
"""
* Script to run a system command recursively in every subdirectory
* in a directory, including the current working directory
* Usage: run_cmd.py -[si] -c <command-to-run>
*
* Options:
* -i
* Interactive mode. Prompts user to choose whether or not to
* run the command in a directory
* -s
* Skips the command for the working directory
* -c
* Command to be run
*
* Example: $python run_cmd.py -s -c <command-to-run>
* This will run 'ls -l > contents.txt' in every subdirectory in the tree
* recursively, but will not run it in the working directory
*
* Author: Arun Vijayshankar
"""
import getopt
import os
import sys
def recursive_run_cmd_inter(root, cmd):
for file in os.listdir(root):
d = os.path.join(root, file)
if os.path.isdir(d):
os.chdir(d)
run = input("Do you want to run " + cmd + " in: \n" + os.getcwd() + " [Y/No]")
if str(run).upper() in ['Y', 'YES']:
print("running " + cmd + " in: " + os.getcwd())
os.system(cmd)
recursive_run_cmd_inter(d, cmd)
def recursive_run_cmd(root, cmd):
for file in os.listdir(root):
d = os.path.join(root, file)
if os.path.isdir(d):
os.chdir(d)
print("running " + cmd + " in: " + os.getcwd())
os.system(cmd)
recursive_run_cmd(d, cmd)
def entry():
argv = sys.argv[1:]
try:
options, args = getopt.getopt(argv, "s:i:c", [])
except:
print("Usage: run_cmd.py -[si] -c '<command-to-be-run>'")
root = os.getcwd()
cmd = args[0]
print(cmd)
if '-i' in options[0]:
recursive_run_cmd_inter(root, cmd)
if '-s' in options[0]:
if '-i' in options[0]:
recursive_run_cmd_inter(root, cmd)
else:
recursive_run_cmd(root, cmd)
else:
os.chdir(root)
print("running " + cmd + " in: " + os.getcwd())
os.system(cmd)
recursive_run_cmd(root, cmd)
if __name__ == "__main__":
entry()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment