该代码不起作用。 (尝试在 for 循环中声明数组值并对它们执行数学函数)

该代码不起作用。 (尝试在 for 循环中声明数组值并对它们执行数学函数)

我再次感到无聊,查找了要在 bash 中制作的程序列表,并且我正在尝试制作一个 CC(信用卡)验证器。我必须将字符拆分为数组才能进行验证,我认为我做错了什么。我不太擅长编码,所以我真的不明白我的代码做错了什么。

代码:

#!/bin/bash
getchecknumber(){ # get the last digit of the cc number
    str=$1
    checknum=$(echo {str: -1})
}
getrest(){ # get the rest of the numbers in the sequence
    sequence=$(echo {str%?})
}
doubleeveryother(){ # double every other number
    # split characters into an array
    arr=()
    i=0
    while [ "$i" -lt "${#str}" ]; do 
    arr+=(${str:$i:1})
     i=$((i+1))
done
for ((i=1; i<=15; i++))
    do {
        char=$(echo "$i-1" | bc)
        double=$(echo "${arr[$char]} * 2" | bc)
        if (( $i % 2 == 0 )) ; then #check if number is 'every other' (divisible by 2)
            foo=bar #do nothing
        else
            arr[$char]=$double #replace the number in the array
        fi
        }
    done
}
adddigitsum() { #split a two digit number into two numbers and add them
    NUMSPLIT=(0 0)
    for ((a=0; a<=14; a++))
    do {
        number=$(echo ${arr[$a]})
        if ((number>=10)) ; then
            for ((b=0; b<=1; b++))
            do
                NUMSPLIT[$b]=$( echo ${number:$n:1} )
            done
            addeddigit=$( echo "${NUMSPLIT[0]} + ${NUMSPLIT[1]}" | bc )
            arr[$a]=$addeddigit # replace the number in the array
        fi
        }
    done
}
addall(){ #add all the digits
    sum=$( IFS="+"; bc <<< "${arr[*]}" )
}
multiply(){ #multiply by 9
    result=$( echo "$sum * 9" | bc )
}
validate(){ #see if the last number of 'result' is equal to the checknum
    resultchecknum=$(echo {string%?})
    if [[ $resultchecknum == $checknum ]] ; then
        echo "CC Number is valid!"
    else
        echo "CC Number is not valid."
    fi
}

getchecknumber
getrest
doubleeveryother
adddigitsum
addall
multiply
validate

输出:

./cc-validator.sh 4000000000000000
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
CC Number is not valid.

相关内容