0

I'm writing a VERY simple bash script with an "IF" statment. I've written many before, but for some reason it will not read the "${hitA1} == 0" argument. ${hitA1} is read from a file, and it is actually reading it, and it does actually equal 0. Instead it goes to the second argument of "${hitA1} != 0". Any ideas?

Code:

CorHitA1=0
MissA1=0
for i in 44 50 53 58 71
do
    late=`expr $i + 1`
    hitA1=`sed -n ${i}p _TMP_Acc1.txt`
    hitlateA1=`sed -n ${late}p _TMP_Acc1.txt`
    if [[ ${hitA1} == 0 ]]; then
        echo "HEY!!!!!"
        CorHitA1=`expr ${CorHitA1} + 1`
    elif [[ ${hitA1} != 0 ]]; then
        echo "Nope..."
        echo ${hitA1}
    fi
    echo "CorHitA1 = " ${CorHitA1}
done
  • 1
    Add `set -x` to the top of your script (after `#!/bin/bash`). It'll give you a bunch of debugging output which should make it easier to figure out what's going wrong – Digital Trauma Dec 13 '13 at 16:39
  • Try adding `set -x` at the top of your script to trace the execution when running it. What's the values then? Try using `if (( ${hitA1} == 0 )); then # yes; else # nope; fi` instead. –  Dec 13 '13 at 16:39
  • Another [answer I found](http://stackoverflow.com/questions/669452/is-preferable-over-in-bash-scripts#answer-669486) says that `[[ ... ]]` is not POSIX-compliant and may not work if you got the bash script from another platform. – Alex W Dec 13 '13 at 16:50

1 Answers1

0

With bash, you should use (( for arithmetic tests:

if ((hitA1 == 0)); then ...

(With arithmetic evaluation, you don't need the $ nor do you need to quote the variable.)

Or you can use the -eq operator with [[:

if [[ $hitA1 -eq 0 ]]; then ...

If you don't do one of the above, and the line in the file you're extracting has whitespace in it, then [[ $hitA1 == 0 ]] will return false because == is string equality, and a string with whitespace is not the same as a string without.

rici
  • 234,347
  • 28
  • 237
  • 341
  • I tried using `if ((hitA1 == 0)); then...` but I got an error message saying `")syntax error: invalid arithmetic operator (error token is "` – user3100107 Dec 13 '13 at 17:45
  • @user3100107: don't use windows editors to edit bash scripts. You're running into problems with stray carriage return characters, part of the windows `CRLF` line ending protocol. Use `dos2unix` or some such to get rid of them. Also: what version of bash are you using? – rici Dec 13 '13 at 20:28