Bash Patterns I Use Weekly

1. Find and replace a pattern in a codebase with capture groups

git grep -l pattern | xargs gsed -ri 's|pat(tern)|\1s are birds|g'

2. Use while loops to re-run a command until it starts failing (or succeeding)

while command; do git checkout HEAD^; done;

This command will continue to run a check until a commit causes it to start failing. It's a lazy git bisect.

3. Parallelize running commands by grabbing PIDs.

pids="";
do_thing_1 &
pids="$pids $!"
do_thing_2 &
pids="$pids $!"
EXIT_CODE=0
for p in $pids; do
  if ! wait $p; then EXIT_CODE=1; fi
done

exit $EXIT_CODE;

4. Use $SECONDS to track how long things take

echo "Your command completed after $SECONDS seconds";