0

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?

icecity96
  • 1,177
  • 12
  • 26
  • You don't need to use `expr` at all; use arithmetic expansion: `k=$(($k - $index))`. – chepner Oct 31 '15 at 16:20
  • Use `for ((index=0; index < 10; index++))` for the for loop and `${ISBN:$index:1}` in place of the `cut` pipeline. – chepner Oct 31 '15 at 16:22

1 Answers1

3

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]} ))
chepner
  • 497,756
  • 71
  • 530
  • 681