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
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
 
    
     
    
    In Linux with /dev/urandom:
$ rnd=$(tr -cd "[:digit:]" < /dev/urandom | head -c 9) && echo $rnd
463559879
 
    
    I think this should make it
shuf -i 99999999-999999999 -n 1
 
    
    Because of RANDOM's limited range, it can only be used to retrieve four base-10 digits at a time. Thus, to retrieve 9 digits, you need to call it three times.
If we don't care much about performance (are willing to pay process substitution costs), this may look like:
#!/usr/bin/env bash
get4() {
  local newVal=32768
  while (( newVal > 29999 )); do # avoid bias because of remainder
    newVal=$RANDOM
  done
  printf '%04d' "$((newVal % 10000))"
}
result="$(get4)$(get4)$(get4)"
result=$(( result % 1000000000 ))
printf '%09d\n' "$result"
If we do care about performance, it may instead look like:
#!/usr/bin/env bash
get4() {
  local newVal=32768 outVar=$1
  while (( newVal > 29999 )); do # avoid bias because of remainder
    newVal=$RANDOM
  done
  printf -v "$outVar" '%04d' "$((newVal % 10000))"
}
get4 out1; get4 out2; get4 out3
result="${out1}${out2}${out3}"
result=$(( result % 1000000000 ))
printf '%09d\n' "$result"
 
    
    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
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.
 
    
    Use perl, as follows :
perl -e print\ rand | cut -c 3-11 
Or
perl -MPOSIX -e 'print floor rand 10**9'
