I have written a script that generate 6 digit random OTP number Is there any simple approach to get 6 digit OTP number with less lines of code [Concise code]

My code :



for (( i =1 ; i<=5 ; i++))
    store_digit=$(shuf -i0-9 -n1) ; dynamic_array+=("$store_digit")
str_array_value="${dynamic_array[*]}" ; echo "Output : ${str_array_value// /}" 
  • for ((i=1; i<=6; i++)); do printf "%d" $((RANDOM %10)); done; echo, subject to there being a very slight bias away from 8 and 9 Nov 9, 2020 at 13:28
  • 1
    printf '%06d\n' "$(shuf -i0-999999 -n1)" perhaps? Nov 9, 2020 at 13:29
  • @steeldriver can you explain command in detail : printf '%06d\n' "$(shuf -i0-999999 -n1)" Nov 9, 2020 at 14:01
  • @codeholic24 if you check the manpage for the shuf command you will see that it accepts a -iLO-HI range. The printf command just ensures that the result is printed exactly 6 digits wide i.e. adds leading zeros as appropriate. Nov 9, 2020 at 14:22

3 Answers 3


If you want to generate actual OTP tokens generated from a shared secret, and not just random six-digit strings you have no way of verifying, you can use oathtool.

Otherwise, steeldriver’s comment should suffice: printf '%06d\n' "$(shuf -i0-999999 -n1)".


For 6 decimal digits, we'll need a random number that's larger than 15-bit. Here, I'll use a 30-bit random:

((RND=RANDOM<<15|RANDOM)) ; echo ${RND: -6}

EDIT: Just a couple of tests, for perspective...

~# time for i in {0..2000} ;do printf '%06d\n' "$(shuf -i0-999999 -n1)" >/dev/null ;done

real    0m13.814s
user    0m9.573s
sys     0m4.302s

~# time for i in {0..2000} ;do ((RND=RANDOM<<15|RANDOM)) ; echo ${RND: -6} >/dev/null ;done

real    0m0.120s
user    0m0.101s
sys     0m0.019s

The question can be re-defined as: "Output a random 6-character string containing characters from a subset of UTF-8: {0,1,2,3,5,6,7,8,9}".

This leads to:

cat /dev/urandom | tr -dc 0-9 | head -c 6
  • 1
    That is rather wasteful. base64 encode the random output and get digits from that, at least.
    – muru
    Mar 15 at 0:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .