Skip to content

Instantly share code, notes, and snippets.

@legeyda
Last active February 9, 2022 15:20
Show Gist options
  • Save legeyda/8b2cf2c213476c6fe6e25619fe22efd0 to your computer and use it in GitHub Desktop.
Save legeyda/8b2cf2c213476c6fe6e25619fe22efd0 to your computer and use it in GitHub Desktop.
bash script to execute given command in all subdirectories of current directory
#!/usr/bin/env bash
USAGE="Usage:
$0 dir1 dir2 dir2 -- command"
# show help if requested
if [ "x$1" == "x-h" -o "x$1" == "x-?" -o "x$1" == "x--help" ]; then
echo "Execute command in each subdirectory of current directory."
echo "$USAGE"
exit 0
fi
# assert arguments supplied
if [ "x$1" == "x" ]; then
echo "foreach: no input, '$0 -h' for help"
echo "$USAGE"
exit 1
fi
# parse dirs
DIRS=
while [ "x$1" != "x" ]; do
if [ "x$1" == "x--" ]; then
shift;
break;
fi
if [ "x$DIRS" != "x" -a "x$2" == "x" ]; then
break;
fi
DIR="$1"
# before starting commands check all folders exist
if pushd "$DIR" > /dev/null ; then
popd > /dev/null
else
echo "foreach: error entering $DIR, dry exiting"
exit 3
fi
DIRS="$DIRS
$DIR"
shift;
done || exit $?
# assert command is set
if [ "x$1" == "x" ]; then
echo "foreach: no command, '$0 -h' for help"
echo "$USAGE"
exit 2
fi
# execute commands
echo "$DIRS" | while read DIR; do
if [ "x$DIR" != "x" ]; then
if pushd "$DIR" > /dev/null ; then
echo "======== entering $DIR ========"
if bash -c "$*" ; then
echo -n
else
echo "foreach: got result code $?, exiting"
exit 4
fi
popd > /dev/null
echo
else
echo "foreach: error entering $DIR, exiting"
exit 3
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment