7
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?

1
  • 2
    Please take a look: shellcheck.net Commented Aug 25, 2016 at 5:08

3 Answers 3

11

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

Comments

5

You need a space before ]].

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

Comments

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 

5 Comments

your logic processing is very smart, but you had not resolved the question yet. Integrate your logic processing with Benjamin W. and Barmar 's answer the final result is perfect :)
That assignment line in the for loop has syntax errors.
@BenjaminW. You are right, it does not use $(( )) in the array's index calculations.
@南山竹 That's not the problem, the index calculation is in an arithmetic context and works like this, but the assignment uses spaces around the = sign!
@BenjaminW. Thanks for spotting that, fixed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.