Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

why the code below, supposed to display a random from 2-3 range, actually works as if the range was 2-4?

echo $((RANDOM%3+2))
share|improve this question
10  
Who supposes such thing? Interval length of 3 (range 0..2) and minimum value of 2 – that is 2..4 for me. –  manatwork Feb 13 '13 at 14:17
add comment

2 Answers

To answer your question:

  • RANDOM%3 has 3 possible values:

0, 1 and 2

+2 then:

2, 3 and 4

share|improve this answer
add comment

Try doing this instead if you want a reliable way :

intrandfromrange() { echo "$(( ( RANDOM % ($2 - $1 +1 ) ) + $1 ))"; }
intrandfromrange 2 4
share|improve this answer
    
No need double quotes around an integer Stephane =) –  sputnick Feb 13 '13 at 22:36
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.