Eitan Myron
Eitan Myron

Reputation: 159

bash expr syntax error when multiplying variable by integer

I am attempting to learn bash, and I tried making a simple bash script to test my terminal. However, when using the expr command, the system keeps telling me that the syntax for the expr command is wrong. Here is the script:

#!/bin/bash
declare -a typo
x=0
y=25
function arrayAndDisplay {
    for x in y;
    do
        typo[x]= `expr $x * 25`
        echo ${typo[x]}
    done
}
arrayAndDisplay

When I try running the script in the terminal, this is the error message I get:

expr: syntax error

I've looked at reference websites and other StackOverflow posts, but nothing seems to work. Can anyone help me?

P.S: I use Mac OS X Yosemite (10.10.1)

Upvotes: 0

Views: 3257

Answers (3)

liushan CHEN
liushan CHEN

Reputation: 821

The expr syntax in mac OS is

$(($x*25))

rather than

`expr $x \* 25`

Upvotes: 2

SMA
SMA

Reputation: 37083

Three things:

  1. for x in y; should be for x in $y;
  2. typo[x]=expr $x * 25`` Remove space between left and right of "="
  3. typo[x]=expr $x * 25`` Remove back ticks as its discouraged and use $(...) Alos you should escape "*" as it has a meaning and is expanded to show all the files in current directory. So you should use it like:

    typo[x]=$(expr $x \* 25)
    

Upvotes: 1

Joe
Joe

Reputation: 31085

The * in your expr is being expanded, so you're actually passing a list of files rather than a multiplication sign. Escape it:

    typo[x]= `expr $x \* 25`

Upvotes: 1

Related Questions