# Bash help - if then syntax, random number generator

#### arduinolego611

Joined Jan 23, 2022
24
I am trying to produce a random number, then, if that number is 5, echo "winner". if the number isn't 5, it should echo "loser".

So the random number part works, but for whatever reason it always prints loser even if 5 does come up from the random number generator. how do I fix this?

Code:
#!/bin/bash

NUMBER=$((1 + RANDOM % 10)) echo$NUMBER

#### arduinolego611

Joined Jan 23, 2022
24
You are using a string comparison on an integer.

Try if $NUMBER -eq 5 good to know...noted. unfortunately that doesn't seem to fix the problem. #### djsfantasi Joined Apr 11, 2010 8,884 I’m not familiar with these Bash commands enough… What is the range of RANDOM numbers? And what’s the probability of RANDOM being exactly equal to 4? Thread Starter #### arduinolego611 Joined Jan 23, 2022 24 I’m not familiar with these Bash commands enough… What is the range of RANDOM numbers? And what’s the probability of RANDOM being exactly equal to 4? I made the range 1-10 #### Ya’akov Joined Jan 27, 2019 7,413 Sorry, it was late when I answered and I left out the brackets. Try: if [$NUMBER -eq 5 ]

Numerical tests require the brackets. If not, bash will interpret the "5" as the name of a program to execute.

#### arduinolego611

Joined Jan 23, 2022
24
Sorry, it was late when I answered and I left out the brackets.

Try: if [ $NUMBER -eq 5 ] Numerical tests require the brackets. If not, bash will interpret the "5" as the name of a program to execute. great, it works now... and thank you for your help. your answers about strings vs integers and brackets for numerical tests give me a trail to follow to learn more about bash. #### Ya’akov Joined Jan 27, 2019 7,413 bash scripts are surprisingly capable though I find the syntax clumsy and some things require kind of odd methods. But it has a of functionality. You might also want to know about shell functions. They are like aliases but they run before the shell does any evaluation. All yo have to do is put some code after a function name. You an do it at the prompt, or from a file, like .profile. For example: bash shell function: yaakov:~$ try () (
while [ 1 ]; do
NUMBER=$((1 + RANDOM % 10)) echo$NUMBER
if [ $NUMBER -eq 5 ] then echo WINNER; exit else echo LOSER fi done; ) yaakov:~$ try
4
LOSER
10
LOSER
7
LOSER
9
LOSER
8
LOSER
7
LOSER
5
WINNER
yaakov:~\$