Created
May 1, 2020 10:50
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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