I
I
Ilya Balabanov2016-01-05 01:36:07
linux
Ilya Balabanov, 2016-01-05 01:36:07

What does the for loop do in this bash function?

Good day! Help me understand what is happening in the for loop (implementation of the Luhn algorithm for bank cards). Thanks

function validate {
num=$1 

   len=${#num} 

    is_odd=1 
    sum=0
     
    for((t = len - 1; t >= 0; --t)) {
        digit=${num:$t:1} #????

        if ; then 
            sum=$(( sum + $digit ))
        else
            sum=$(( $sum + ( $digit != 9 ? ( ( 2 * $digit ) % 9 ) : 9 ) ))
        fi

        is_odd=$(( ! $is_odd ))
    }

    # NOTE: returning exit status of 0 on success
    return $(( 0 != ( $sum % 10 ) ))
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
abcd0x00, 2016-01-05
@abcd0x00

What does the for loop do in this bash function?

It simply takes each character from num in reverse order.
[[email protected] ~]$ s=abcd
[gues[email protected] ~]$ echo "${s:0:3} ${s:0:2} ${s:2:1}"
abc ab c
[[email protected] ~]$

A
Artem Spiridonov, 2016-01-05
@customtema

The suma variable is not declared.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question