L'Agatha
L'Agatha

Reputation: 43

Problem with if/else statement and operator multiplication operator (*) in shell script

I'm very new to shell scripting. Basically my little program takes 2 inputs: a number and an mathematical operator and then prints out a maths table for said number & operator (1 + 2 = 3, 2 + 2 = 4 etc.)

The program runs fine until I get to: elif [[ $op == * ]] This statement evaluates to true even when the operator I input is the division operator (/) or exponentiation operator (^). Any help appreciated!

Upvotes: 1

Views: 406

Answers (2)

rcwnd_cz
rcwnd_cz

Reputation: 1016

Using unquoted strings blindly is very problematic in shell. Rule of thumb is always quote all strings which are meant to be taken literally (as-they-are). Otherwise they will be expanded like in your case.

Literal * in shell will get expanded and then unwanted results will happen.

So, lets revise how can we escape strings in shell.

  • \ backslash. In your case [[ "$op" == \* ]]
  • ' single quotes. Example: [[ "$op" == '*' ]]
  • set -o noglob. In most shells, this will prevent expansions to happen at all.

Upvotes: 2

Mikołaj Głodziak
Mikołaj Głodziak

Reputation: 5277

first of all I can see many syntax errors. Look at working code:

num=$1
op=$2

if [[ $op = '+' ]]
then
    for ((i=1; i<15; i++)); do
        sum=$((i + num))
        echo $i " + " $num " = " $sum
    done

elif [[ $op = '-' ]]
then
    for ((i=$num; sum<14; i++)); do
        sum=$((i - num))
        echo $i " - " $num " = " $sum
    done

elif [[ $op = '*' ]]
then
    for ((i=1; i<15; i++)); do
        sum=$((i * num))
        echo $i " * " $num " = " $sum
    done

elif [[ $op = '/' ]]
then
    for ((i=1; sum<15; i++)); do
        sum=$((i / num))
        echo $i " / " $num " = " $sum
    done

else
    for ((i=1; i<15; i++)); do
        sum=$((num ** i))
        echo $num " ^ " $i " = " $sum
    done
fi
  1. In the if-statements you need to use single = character. Look at man test. In the if-statements invoked is test command. So if you need to compare strings you need to use single = character.
  2. Put operators into quotes. It will be helpful to compare strings.
  3. It's time to start script. Make sure, that it has execute privileges and this script is in your current directory. If yes, you can run it (example running): ./yourscript.sh 3 '*' You should run this script in this way. Put the operator in the single quotes. The problem with * is, because star is a meta character. Put star into a quotes and your script should work. :)

Upvotes: 1

Related Questions