0

I am in the very early stages of learning Unix scripting. I've written a Bash script which does not generate any errors, but clearly has a logic error, as the IF test always gives the same response.

I have tried various variations on the theme of my IF, but still end up with the same result.

#!/bin/bash

declare -i number1
declare -i number2
declare -i total

declare operation

echo "Enter a, s, m or d for add, subtract, multiply or divide"
read operation

echo "Enter number 1"
read number1
echo "Enter number 2"
read number2

echo "operation="$operation

if [ $operation=='m' ]
then 
    total=$number1*$number2
elif  [ $operation=='a' ]
then 
    total=$number1+$number2
elif [ $operation=='d' ]
then 
    total=$number1/$number2
elif [ $operation=='s' ]
then 
    total=$number1-$number2
fi

echo $number1 " multiplied by " $number2 " equals " $total
exit 0

It doesn't matter whether I enter a, s or d (or indeed m) in response to the first prompt, my script always does a really nice multiplication... The line

echo "operation="$operation

correctly shows the operator I've requested.

Any ideas what I've done wrong?

Many thanks

Andrew Richards
  • 321
  • 1
  • 9

1 Answers1

1

You need to add spaces around all the ==. That's it. Instead of

if [ $operation=='m' ]

you should have:

if [ $operation == 'm' ]
  • 1
    Should be `[ "$operation" = m ]` to be compatible with all possible `operation` values and non-bash shells (`=` is the only POSIX-specified string comparison operator; expansions, but not literals, need quoting). That said, as this question is asked-and-answered already, the appropriate action is to vote to close this instance as a duplicate, not to add another answer. See https://stackoverflow.com/help/how-to-answer, particularly the "Answer Well-Asked Questions" section, particularly the bullet point regarding questions which "have already been asked and answered many times before". – Charles Duffy Sep 30 '19 at 15:02
  • ...for a specific example of a case where `[ $operation == 'm' ]` will fail even on shells where `==` works, try with an operation of `*`; instead of just getting a false result you'll get a syntax error, because the `*` will be replaced with a list of filenames in the current directory before it's passed to the `[` command. – Charles Duffy Sep 30 '19 at 15:06
  • Anyhow, much of the point of closing something as duplicate is that the canonical instance can collect answers that have already been vetted, refined and edited; whereas when you write a new answer on a new instance, all the work needed to make it pedantically correct and well-resourced is yet to be done. – Charles Duffy Sep 30 '19 at 15:07