lundi 30 septembre 2019

Bash script if not processing as I would expect

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

Aucun commentaire:

Enregistrer un commentaire