Skip to content

Instantly share code, notes, and snippets.

@ejmr
Created August 17, 2018 23:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ejmr/e2edeb39c8f388b1b97ee3578b468a0a to your computer and use it in GitHub Desktop.
Save ejmr/e2edeb39c8f388b1b97ee3578b468a0a to your computer and use it in GitHub Desktop.
Perform Arbitrary Commands on Immediate Subdirectories
#!/bin/sh
#
# for-each-subdir
# ===============
#
# ## SYNOPSIS
#
# $ for-each-subdir [FLAGS]
#
# ## DESCRIPTION
#
# Lists all immediate sub-directories. Any given `FLAGS` appear at the
# end of the call to `fd`, which allows you, for example, to use the `-x`
# flag to run some command for each sub-directory. Or you can use the
# `--print0` flag and pipe the output into `xargs -0`.
#
# ## EXAMPLES
#
# Fetch updates for all Git repositories which are within sub-directories
# of the current directory:
#
# $ for-each-subdir -x git -C '{}' fetch origin
#
# Show the disk usage of each sub-directory.
#
# $ for-each-subdir -0 | xargs -0 du -h
#
# ## REQUIREMENTS
#
# fd: https://github.com/sharkdp/fd
#
# ## COPYRIGHT
#
# Eric James Michael Ritz, 2018
#
# ## LICENSE
#
# CC0 1.0 Universal
# <https://creativecommons.org/publicdomain/zero/1.0/legalcode>
#
# ## SEE ALSO
#
# fd(1)
#
########################################################################
fd --type d --max-depth 1 --absolute-path --color never $@
@ejmr
Copy link
Author

ejmr commented Aug 17, 2018

Here is an example of a script I use which builds upon this one. I call it update-git-projects-in-subdirs. Its contents are:

#!/bin/sh

for-each-subdir -x git -C '{}' fetch origin
for-each-subdir -x git -C `{}` merge --ff-only "@{upstream}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment