Ubuntu: Why does my condition always evaluate as true?



Question:

I'm writing my first bash script and I've hit a snag. Here's an example where I ask for a name, ask for an age, and display a message that changes depending on whether or not the age is <= 35:

#!/bin/bash  ageLimit = 34  echo "What is your name?"  read userName  echo "How old are you?"  read userAge  if (( "$userAge" -le "$ageLimit" )); then      echo "Hey, $userName.  At $userAge years old, you are young."  else      echo "Gosh, $userName.  At $userAge years old, you're pretty old."  fi  

No matter what number I answer for age, I am told I am young. This is running on Raspbian -- in case that helps. Thanks!

Jeremy


Solution:1

Whitespaces make a lot of difference in whell script, you need to take care of them. There is no space between the variable name and the = sign and its value.

Rewrite your shell script as follows:

#!/bin/bash  ageLimit=34  echo "What is your name?"  read userName  echo "How old are you?"  read userAge  if [[ "$userAge" -le "$ageLimit" ]]; then      echo "Hey, $userName.  At $userAge years old, you are young."  else     echo "Gosh, $userName.  At $userAge years old, you're pretty old."  fi  

Refer to a good tutorial on shell scripting while you make your hands dirty. One good tutorial googling returns is this:

You may also want to know this:


Solution:2

I can see two minor errors in your code.

[1] Do not use space while declaring variable, do like this

ageLimit=34  

[2] There is two ways of putting if conditions, use either of it.

if [ "$userAge" -le "$ageLimit" ]; then  

or

if (( "$userAge" <= "$ageLimit" )); then  


Solution:3

if you are try to evaluate two string then use the -le -ge if you want to evaluate the number i suggest you to use the conventional operator > <= it is general convention and wars good. so in this case use

if [ "$userAge" -le "$ageLimit" ]; then else fi


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »