r/codegolf • u/l2golf • May 21 '14
[bash] 99 bottles [all]
A fun classic, I decided to golf in bash. got it down to 375 characters
d(){ N=$1;S1=" of beer on the wall";S2="Take one down and pass it around";S3="Go to the shop and buy some more";b $N;echo -n "$S1, ";b $N;echo "${S1:0:8}.";N=$(($N-1));if [[ $N -lt 0 ]];then N=99;S2=$S3;Q=1;fi;echo -n "$S2, ";b $N;echo -e "$S1.\n";if [[ $Q != 1 ]];then d $N;fi;};b(){ case $1 in 1)S="1 bottle";;0)S="No more bottles";;*)S="$1 bottles";;esac;echo -n $S;};d 99Here it is before I turned it into a one-liner
#!/bin/bash
drink() {
N=$1
S1=" of beer on the wall"
S2="Take one down and pass it around"
S3="Go to the shop and buy some more"
bottles $N; echo -n "$S1, "
bottles $N; echo "${S1:0:8}."
N=$(($N-1))
if [[ $N -lt 0 ]]; then
N=99
S2=$S3
Q=1
fi
echo -n "$S2, "
bottles $N; echo -e "$S1.\n"
if [[ $Q != 1 ]]; then
drink $N
fi
}
bottles() {
S=" bottles"
case $1 in
1) S="1${S:0:7}";;
0) S="No more$S";;
*) S="$1$S";;
esac
echo -n $S
}
drink 99Additional challenge: golf it in under 140 so it's tweetable
4
Upvotes
View all comments
2
u/looksLikeImOnTop May 30 '14
This is my first time golfing! Got it down to 222 in Python 3.x, previous versions do not support prints in generators. Could probably shave it down a little more to about 210
I'm still trying to figure out how to make it one line!