Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script number generator

Tags:

bash

shell

I need to generate random numbers in an specific format as test data. For example, given a number "n" I need to produce "n" random numbers and write them in a file. The file must contain at most 3 numbers per line. Here is what I have:

#!/bin/bash

m=$1
output=$2

for ((i=1; i<= m; i++)) do
    echo $((RANDOM % 29+2)) >> $output
done

This outputs the numbers as:

1
2
24
21
10
14

and what I want is:

1 2 24
21 10 14

Thank you for your help!

like image 221
Sergio Avatar asked Feb 15 '23 00:02

Sergio


1 Answers

Pure bash (written as a function rather than a script file)

randx3() {
  local d=$'  \n'
  local i
  for ((i=0;i<$(($1 - 1));++i)); do
    printf "%d%c" $((RANDOM%29 + 2)) "${d:$((i%3)):1}"
  done
  printf "%d\n" $((RANDOM%29 + 2))
}

Note that it doesn't take a file argument; rather it outputs to stdout, so you would use it like this:

randx3 11 > /path/to/output

That style is often more flexible.

Here's a less hacky one which allows you to select how often you want a newline:

randx() {
  local i
  local m=$1
  local c=${2:-3}
  for ((i=1;i<=m;++i)); do
    if ((i%c && i<m)); then
      printf "%d " $((RANDOM%29 + 2))
    else
      printf "%d\n" $((RANDOM%29 + 2))
    fi
  done
}

Call that one as randx 11 or randx 11 7 (second argument defaults to 3).

like image 115
rici Avatar answered Feb 24 '23 02:02

rici