Self modifying shell script – unrolling a loop

Some shell scripting languages read scripts as they are interpreted. I wrote this script as an experiment in looping without a loop. This functioned on an older version of ksh on HP-UX, but I haven’t been able to find a newer version of a shell that this still works on.

# This script returns 0 through n-1, where n is given as $1

LSRT=`echo "/[L]OOP/#\nq!" | ex -s -c - $0 | awk '{print $1+1}'`
LEND=`echo "/[P]OOL/#\nq!" | ex -s -c - $0 | awk '{print $1-1}'`
END=$((`wc -l < $0` + 1))

#LOOP
if [ "$VAL" -lt "$1" ]
then echo "${LSRT},${LEND}co\$\nwq"
printf "%d\n" $VAL > “/dev/tty”
else echo “\$a\n\n.\n${END},\$d\nwq”
fi | ex -s -c - $0
VAL=$(($VAL + 1))
#POOL

Leave a Reply

Your email address will not be published. Required fields are marked *