0

I have 2 variables in bash. Using test i found out that one of them is integer and other one is string. I want to compare them and see if they are equal. I tried the following options.

if [ "$a" -eq "$b" ]

if [[ "$a" -eq "$b" ]]

if [ "$a" = "$b" ]

if [[ "$a" = "$b" ]]

I tried converting the string variable to integer as

a=$(($a+0))

but I got the following error

+0")syntax error: invalid arithmetic operator (error token is "

None of them are providing me the expected result. Please tell me what I am doing wrong?

I have multiple CSV files. The second field of the last row in each of these files will contain the number of rows in that file. I have to get the row count from the file and compare it against the actual number of rows in the file. If they are same, then only I have to process.

ROW_COUNT=`grep -c ^ /tmp/file1.csv` --This is the number

LAST_LINE=`tail -n 1 /tmp/file1.csv`
ACTUAL_ROW_COUNT=`echo ${LAST_LINE} | cut -d "," -f 2` --This is the string

--now i am comparing these two numbers to see if they are same.
if [[ ${ROW_COUNT} == "${ACTUAL_ROW_COUNT}" ]]; then -- Here it is breaking
  • 2
    -eq will compare them as integers, = will compare them as strings. You don't need to convert the string first. – Barmar Sep 20 '15 at 5:07
  • 2
    I can't reproduce that error. What was the original value of $a, and what is the exact statement you used? – Barmar Sep 20 '15 at 5:10
  • 1
    What's the difference between your third and fourth options? – Scott Sep 20 '15 at 6:48
0

The following if statement worked for me.

if [[ ${a} = *"${b}"* ]]; then
  • 1
    Why so complicated?  This will report TRUE if $a contains $b; e.g., a=foo42bar and b=42, or a=1942 and b=94. – Scott Sep 20 '15 at 6:48
0

Have you tried with (())? it is used for numbers instead of characters. So the comparison would be:

 if (( "$a" == "$b" ))

Mind the double == it is important.

  • I tried this. It did not work for me. – stany Sep 21 '15 at 9:38
  • @stany could you echo the values before the if? what values do $a and $b have before the if loop? – YoMismo Sep 21 '15 at 9:47
  • i echoed both values. both have same value. In my example, ACTUAL_ROW_COUNT is string. I tried ACTUAL_ROW_COUNT=expr $ACTUAL_ROW_COUNT + 0 , but it gives me "expr: non-numeric argument" error. – stany Sep 21 '15 at 10:05
  • @stany I must be missing something... Is the problem that ACTUAL_ROW_COUNT sometimes returns a number and sometimes returns a string? in that case, you have to process that variable before you compare it. – YoMismo Sep 21 '15 at 10:19
  • 1
    Weird, if I do a x="03 " and after that I do a echo $(($x+1)) I am returned 4. I guess what you have after the number is some special character. Anyway, I'm glad you solved it. – YoMismo Sep 21 '15 at 10:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.