2

Here I see the [[ allows comparison between string and integer.

    [usr1@host dir]$ echo $count1
    [1] "0"

    [usr1@host dir]$ echo $count2
    13188

    [usr1@host dir]$ if [[ $count1 -ne $count2 ]]
    > then
    > echo "NE"
    > fi
    bash: [[: [1] "0": syntax error: operand expected (error token is "[1] "0"")

   #this worked fine at one point
   if [[ $count1 -ne $count2 ]] then
      echo "NE"
   fi
   syntax error near unexpected token 'then'  

   if [[ $count1 -ne $count2 ]];    then
      echo "NE"
   fi
   [[: [1] "0": syntax error: operand expected (error token is "[1] "0"")

I am very confused with the way the syntax works. How do we tackle different scenarios? How to prevent the syntax errors irrespective of the value changes(im guessing thats the reason it gives error now).

ilkkachu
  • 138,973
sjd
  • 135
  • (1) Does your $count1 value really include brackets and quotes?  What sort of result do you expect from input like that? (2) In your first example, the ]] and the then are on different lines.  If you put them on the same line, you must put a ; between them. – G-Man Says 'Reinstate Monica' Dec 19 '18 at 05:54
  • @G-Man Simply comparing the count of records from 2 different sources. Which syntax should i be using? – sjd Dec 19 '18 at 06:02
  • @G-Man Ooh Sorry .. Now only i understood the "[1]" was part of the output of count1. Will try again.. Thanks – sjd Dec 19 '18 at 06:21
  • @sjd: If the output of count1 is really: [1] "0", then != should be used in if condition to compare the string and a number. Eg: if [[ "$count1" != "$count2" ]] ;then echo "NE"; fi – ashish_k Dec 19 '18 at 06:42

1 Answers1

2

Your count1 variable contains the string [1] "0". This is a eight character string that is not an integer.

Even if the value had been just "0", the test [[ $count1 -ne $count2 ]] with $count1 being "0" is very different from [[ "$count1" -ne "$count2" ]] with $count1 being the single character string 0.

Kusalananda
  • 333,661
  • 1
    even worse, count1 seems to contain the seven characters [1] "0". Same syntax error, though. – ilkkachu Dec 19 '18 at 08:37
  • @ilkkachu Ah, I missed that. I'll update in a few minutes. Thanks! – Kusalananda Dec 19 '18 at 09:17
  • Actually the data in count1 was transferred from a R Function. Which always returns the index [1] with the result. once that issue is resolved i cound fix it thanks – sjd Dec 19 '18 at 12:00