'Modulus function in bash shell script

for ((i=0; i<lenPT; i++)) do 
    if [[ $(($lenPT % 2))  == 0]] then
        P[i] = "$((K [0] * arrT[i] + K[2] * arrT[i+1]))" 
    else
        P[i] = "$((K[1]*arrT[i-1]+K[3]*arrT[i]))"
    fi
done

I got errors saying that "syntax error in conditional expression" and "syntax error near 'then'". What is the error in my conditional statement?



Solution 1:[1]

Space matters, see Barmar's answer. You also need a semicolon after the [[ ]] conditional if you want to put then on the same line.

Instead of the cumbersome [[ $(( )) ... ]] combination, you can use the (Bash-only) (( )) conditional, the contents of which are evaluated in an arithmetic context:

if ((lenPT % 2 == 0)); then

You don't even need $lenPT in this construct, lenPT is enough (see Conditional Constructs in the manual for details).

Since the exit status of ((...)) is 1 (not successful) if the expression evaluates to 0, and 0 (successful) otherwise, you could swap the branches and shorten the condition a little:

if ((lenPT % 2)); then
    P[i]=$((K[1] * arrT[i-1] + K[3] * arrT[i]))
else
    P[i]=$((K[0] * arrT[i] + K[2] * arrT[i+1]))
fi

Solution 2:[2]

You need a space before ]].

   if [[ $(($lenPT % 2)) == 0 ]]; then

Solution 3:[3]

The if ... else that depends on the value of $lenPT is needless, since $lenPT never changes within the loop. The assignments are so similar the if logic can be replaced with arithmetic. Example:

n=$((lenPT % 2))
for ((i=0; i<lenPT; i++)) 
do      
    P[i]="$((K[n] * arrT[i-n] + K[2+n] * arrT[i+1-n]))"
done 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 jwilleke
Solution 3