scvalex.net

3. Loop Unrolling in sh

Here’s a puzzle for you: what does the following shell script do? (works in zsh, bash, dash, BusyBox’s sh, but not tcsh; the script must have a trailing newline)

#!/bin/sh

i=10
echo "I'm going to countdown from $i"

i=$(($i-1))
echo $i
[ $i -ge 1 ] \
  && tail -n6 $0 >> $0 \
  || echo "Ready or not, here I come!"
sleep 1

Answer: it simulates a loop iterating from \(10\) to \(1\). At every iteration, if it is not the last iteration, it appends the “loop’s body” to the script. This works because most shells will read the script lazily line-by-line. The one second delay is there to ensure that the append hits the file system cache before the shell tries to read the next line.

I know a person who took one look at the above and claimed it was the most horrible code they’d ever seen. Although flattered, I know you can do much worse, and I’d love to see some examples in the comments. To clarify, I’m not looking for badly written code (that’s the domain of The Daily WTF), but for code that makes you go “wat?”.