4 ms·
Although not quite as spectacular as that, here is some funny codegen in POSIX shell I wrote; `sh` doesn't have a `repeat` command, so I wrote a script to imple
by ykonstant 3y ago
Although not quite as spectacular as that, here is some funny codegen in POSIX shell I wrote; `sh` doesn't have a `repeat` command, so I wrote a script to implement it without forcing any loops at all. Along the way I uncovered some interesting segfaults for most sh implementations (including, sadly, dash), which is the reason for the somewhat convoluted code. Have fun!
#!/bin/sh
#
# Usage: repeat TIMES COMMAND
# Repeat COMMAND a given number of TIMES.
eval_full_quotes='
s/\\/\\\\/g ; s/\"/\\\"/g ; s/</\\</g ; s/>/\\>/g ;
s/\$/\\\$/g ; s/\[/\\\[/g ; s/*/\\*/g ; s/?/\\?/g ;
s/|/\\|/g ; s/&/\\&/g ; s/~/\\~/g ; s/=/\\=/g ;
s/;/\\;/g ; s/ /\\ /g ; s/%/\\%/g ; s/`/\\`/g ;
s/(/\\(/g ; s/)/\\)/g ; s/{/\\{/g ; s/}/\\}/g ;
s/#/\\#/g ; s/'"'"'/\\'"'"'/g'
errorx() { printf 'Error: %s\n' "${*:-"unknown error."}" >&2; exit 1; }
_rep() {
rep_times="$((2 * $1))"
rep_string="$2"
output=""
while [ 0 -lt "${rep_times}" ]; do
test 1 -eq "$(((rep_times /= 2) % 2))" && output="${output}${rep_string}"
rep_string="${rep_string}${rep_string}"
done
printf '%s' "${output}"
}
{
times="$1"
shift
test 0 -lt "${times}" || errorx "First argument must be a positive integer."
test 0 -lt "$#" || errorx "No command given to repeat."
repeat_command="$*"
command_length="${#repeat_command}"
max_arg="${ARG_MAX:-"$(getconf ARG_MAX)"}"
if [ "${max_arg}" -le "$((times * (command_length + 2)))" ]; then
: "$(( block_size = max_arg / (20 * (command_length + 2)) ))"
: "$(( blocks = times / block_size + 1 ))"
: "$(( remainder = (block_size + (times % block_size)) % block_size ))"
eval_string="$(_rep "${block_size}" "${repeat_command}; " | sed -e "${eval_full_quotes}")"
while [ 0 -lt "$((blocks -= 1))" ]; do
eval eval "${eval_string}"
done
eval_string="$(_rep "${remainder}" "${repeat_command}; " | sed -e "${eval_full_quotes}")"
eval eval "${eval_string}"
else
eval_string="$(_rep "${times}" "${repeat_command}; " | sed -e "${eval_full_quotes}")"
eval eval "${eval_string}"
fi
}
exit