Alex
Alex

Reputation: 7065

Bash if else statement not recognising +/- characters

I am attempting to read a file, line by line, and for each iteration check the fifth array element, which will be a + or - (plus or minus) character. I am able to read the file line by line but cannot get the if/else statement to do recognise the +/-.

Bash code I have written

#!/bin/bash
# save the field separator
old_IFS=$IFS
while IFS=$'\t' read -r -a myArray
do 
    echo "${myArray[5]}"
    if [ $myArray[5] = "+" ]; then
       echo plus
    elif [ $myArray[5] = "-" ]; then
       echo minus
    else
        echo no
    fi
done < /Users/Alex/Desktop/test.bed

# restore default field separator 
IFS=$old_IFS 

Sample input

Scaffold1   34  39  name    .   -
Scaffold1   12  17  name    .   -
Scaffold1   17  12  name    .   +
Scaffold1   43  49  name    .   +
Scaffold1   45  48  name    .   -

Sample output

-
no
-
no
+
no
+
no
-
no

Under each +/- it should say either plus or minus but instead states no, indicating the conditional statements have failed. Once this outputs correctly I will be changing the echo commands to do arithmetic on either column 2 or 3 depending on the sign.

Upvotes: 0

Views: 58

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295639

You need:

${myArray[5]}

Not:

$myArray[5] # this is equivalent to "${myArray[0]}[5]"

By the way, consider a case statement instead:

case ${myArray[5]} in
  -) echo minus ;;
  +) echo plus ;;
  *) echo no ;;
esac

You could also avoid the need for an array -- and thus make your code POSIX sh compatible -- using named arguments to read for each columns:

while IFS=$'\t' read -r scaffold num1 num2 name dot col _; do
  : "$col" refers to your fifth column here
done

Upvotes: 5

Related Questions