#!/usr/bin/env bash # HEADER #======================================================================= # # ring -- Random INteger Generator # # SYNOPSIS # ring n min max # # DESCRIPTION # Shell script to generate a fixed number of random integers # in a given range, by default [1, 10^ceil(log10(n))]. # # OPTIONS # -h|--help display this help and exit # # EXAMPLES # genate n numbers (in range [1, n]) # $ ring n # genate n numbers in range [a, b] # $ ring n a b # # DEPENDENCIES # - GNU coreutils: head, tail, cut, grep, sed, tr # # Copyringht (c) 2019 by Nicolas Mesnier # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 or # above as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # #======================================================================= # END_OF_HEADER #----------------------------------------------------------------------- set -euo pipefail #----------------------------------------------------------------------- # *** read this header to display help #----------------------------------------------------------------------- SCRIPT_NAME="$(basename ${0})" BOH=$(head -200 ${0} | grep -n "^# HEADER" | cut -f1 -d:) EOH=$(head -200 ${0} | grep -n "^# END_OF_HEADER" | cut -f1 -d:) function Help(){ head -$(($EOH-1)) ${0} | tail -$(($EOH-$BOH-1)) \ | grep -e "^#$" -e "^# " \ | sed -e "s/^#=*//g" \ -e "s/\${SCRIPT_NAME}/${SCRIPT_NAME}/g" } #----------------------------------------------------------------------- # *** get options *** #----------------------------------------------------------------------- if [ ${#@} -ge 1 ] ;then case "${1}" in -h|--help) Help exit 0 ;; *) nvalues=${1} ;; esac if [ ${#@} -eq 3 ];then min=${2} max=${3} maxvalues=$((${max}-${min}+1)) if [ ${nvalues} -ge ${maxvalues} ];then msg=" *** Can't generate ${nvalues} intergers " msg+="in range of size ${maxvalues}!" echo ${msg} exit 1 fi else # find n such as 10^{n-1} < nvalues < 10^n n=1 while [ ${nvalues} -ne 0 ];do nvalues=$(( ${nvalues} / 10 )) n=$(($n+1)) done min=1 max=$((10**${n})) fi items=() while [ ${#items[@]} -lt ${nvalues} ] do num=$(( ( RANDOM % (${max}-${min}) ) + ${min} )) if [[ ! "${items[@]}" =~ "${num}" ]]; then items[${#items[@]}]=${num} fi done echo ${items[@]} | tr ' ' '\n' fi #====================================================================eof # vim: set tw=72 ts=2 sw=2 nu: