Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modulus function in bash shell script

Tags:

linux

bash

shell

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?

like image 272
Barani Myat Tun Avatar asked Dec 10 '22 15:12

Barani Myat Tun


2 Answers

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
like image 134
Benjamin W. Avatar answered Jan 04 '23 10:01

Benjamin W.


You need a space before ]].

   if [[ $(($lenPT % 2)) == 0 ]]; then
like image 26
Barmar Avatar answered Jan 04 '23 11:01

Barmar