1

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?

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

1 Answer 1

4

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]} ))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.