This post introduces the ‘$RANDOM’ in Shell including Ksh, Bash and Zsh and gives 2 examples using random processing in Shell. May it help:)
1. Number sequence random order generator
#
# Number sequence random order generator – nsrog
# Generate random order of number sequence based on the range.
# Version 0.0
# Aug 13, 2011
# dave.tian@alcatel-lucent.com
#
[[ -f $PWD/random.nsrog ]] && (rm -f $PWD/random.nsrog) > /dev/null 2>&1
typeset -i counter
counter=1
while (( counter <= 10 ))
do
echo "$counter $RANDOM" >> random.nsrog
(( counter++ ))
done
cat random.nsrog | sort -k2n | cut -d" " -f1 | xargs
/home/daveti/Shelltest: ./nsrog
6 1 2 4 3 5 7 9 8 10
/home/daveti/Shelltest: ./nsrog
3 9 2 10 8 1 4 7 5 6
/home/daveti/Shelltest: ./nsrog
10 4 7 2 1 8 6 9 3 5
/home/daveti/Shelltest:
2. Random line file generator
#
# Random line file generator – rlfg
# Generate random lines of the file.
# Version 0.0
# Aug 13, 2011
# dave.tian@alcatel-lucent.com
#
[[ -f $PWD/random.rlfg ]] && (rm -f $PWD/random.rlfg) > /dev/null 2>&1
while read i
do
echo "$i $RANDOM" >> random.rlfg
done < input.rlfg
cat random.rlfg | sort -k2n | cut -d" " -f1
/home/daveti/Shelltest: cat input.rlfg
this_is_line_1
this_is_line_2
this_is_line_3
this_is_line_4
this_is_line_5
this_is_line_6
this_is_line_7
this_is_line_8
this_is_line_9
this_is_line_10
/home/daveti/Shelltest: ./rlfg
this_is_line_1
this_is_line_9
this_is_line_6
this_is_line_3
this_is_line_8
this_is_line_10
this_is_line_4
this_is_line_7
this_is_line_5
this_is_line_2
/home/daveti/Shelltest: