2011-09-05

How to generate cyclic numbers in ksh

Sometimes, I need to generate limited number of temporary files in loop like below.

while :
do
ps -elf > /tmp/ps.log.$cyclic_number_here
done


Generating cyclic number is an easy job. For example, next function does that.

#! /usr/bin/ksh
GEN_CYCLIC_CALL_COUNT=1
gen_cyclic_number()
{
typeset -i max=$1 mod

((max < 1)) && print 0 && return

((mod = GEN_CYCLIC_CALL_COUNT % max))
if ((mod == 0)); then
((GEN_CYCLIC_CALL_COUNT = max + 1))
print -- $max
else
((GEN_CYCLIC_CALL_COUNT += 1))
print -- $mod
fi
}
But this function will not output the correct numbers when used in command subsititution because it's executed in a subshell.

Correct and easier way is to use proper arithmetic expressions as arithmetic expansion is done in the shell, not in a subshell.

typeset -i i=-1
while :
do
ps -elf > /tmp/ps.log.$((i = (i += 1) % 3)) # generates ps.log.0, ps.log.1, ps.log.2
done


What you need is just 0 and 1, even simpler solution is here.
typeset -i i=1
while :
do
ps -elf > /tmp/ps.log.$((i ^= 1))
done

No comments:

Post a Comment