Search code examples
bashexpr

I am getting an syntax error when using expr


Here is the code:

#!/bin/bash
reg='[0-9]{1}-[0-9]{2}-[0-9]{6}-[0-9Xx]{1}'
while read ISBN; do
    if [[ $ISBN =~ '$$$' ]]; then
        exit 0
    else
        if [[ $ISBN =~ $reg ]]; then
            ISBN=${ISBN//-/}
            let sum=0
            let k=11
            for index in `seq 1 10`; do
                array[$index]=`echo $ISBN | cut -c"$index"`
                k=$(expr $k - $index)
                n=$(expr $k * ${array[$index]})
                sum=$(expr $sum + $n)
                echo $sum
            done
            #do something
        else
            echo Invaild
        fi
    fi
done

My input:

0-00-000001-1

The error:

expr: syntax error
expr: syntax error

but when I run expr in terminal like following:

k=11
index=1
echo $(expr $k - $index)

it works well.Can you tell me why?


Solution

  • With expr, you need to escape the * to avoid it being expanded as a file glob:

    n=$(expr $k \* ${array[$index]})
    

    With arithmetic expressions, this is not an issue:

    n=$(( $k * ${array[$index]} ))