Skip to content

Instantly share code, notes, and snippets.

@s-leroux
Created May 1, 2020 10:50
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 s-leroux/d58289c1b0d5ce5832be155eff75a8cf to your computer and use it in GitHub Desktop.
Save s-leroux/d58289c1b0d5ce5832be155eff75a8cf to your computer and use it in GitHub Desktop.
How to use recursion in Bash? Example: producing all {0..1} combinations of a given length.
#!/bin/bash
# Produces all {0..1} combinations of a given length
#
# This program is provided AS-IS with the sole purpose of
# demonstrating the use of functions and recursion in Bash
#
# Usage:
#
# sh$ ./bin.sh 3
# 000
# 001
# 010
# 011
# 100
# 101
# 110
# 111
run() {
# usage: run count
local count=$1
if [[ $count -gt 0 ]]; then
run $((count-1)) | while read head; do
for tail in {0..1}; do
echo "${head}${tail}"
done
done
else
echo
fi
}
# Parameter validation left as an exercice
# ;)
run $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment