bashshellunixsh

If RANDOM only goes up to 32767, how can I generate a 9-digit random number?


How to generate 9 digit random number in shell?

I am trying something like this but it only gave numbers below 32768.

#!/bin/bash
mo=$((RANDOM%999999999))
echo "********Random"$mo

Please help

output should be ********Random453351111


Solution

  • As a work around, we could just simply ask for 1 random integer, for n times:

    rand=''
    for i in {1..9}; do
        rand="${rand}$(( $RANDOM % 10 ))"
    done
    
    echo $rand
    

    Try it online!


    Note [1]: Since RANDOM's upper limit has a final digit of 7, there's a slightly lesser change for the 'generated' number to contain 8 or 9's.