LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Help on string comparison in bash script... (https://www.linuxquestions.org/questions/linux-newbie-8/help-on-string-comparison-in-bash-script-4175589500/)

mangya 09-15-2016 10:59 AM

Help on string comparison in bash script...
 
Hello All

I'm a mediocre level bash scripter. Following code is making me crazy. I cant understand what I'm doing wrong. I just want to make sure the parameter passed to script is either '264' or '265'.

The problem is in first if statement. The second works fine. Whats wrong in first one?

Code:

#!/bin/bash

echo "Type 1:"
if [[ "$1" != "264" || "$1" != "265" ]] ; then
    echo "Parameter should be 264 or 265"
else
    echo "Correct"
fi

echo "Type 2:"
if [[ "$1" == "264" || "$1" == "265" ]] ; then
    echo "Correct"
else
    echo "Parameter should be 264 or 265"
fi

Result is like this:
Code:

$ ./strcomp.sh abc
Type 1:
Parameter should be 264 or 265
Type 2:
Parameter should be 264 or 265

$ ./strcomp.sh 264
Type 1:
Parameter should be 264 or 265
Type 2:
Correct

$ ./strcomp.sh 265
Type 1:
Parameter should be 264 or 265
Type 2:
Correct

Why != in first if statement comparsion is not working?

Thanks

hazel 09-15-2016 11:19 AM

I think you need && in that first statement, not ||.

Suppose $1 is 254. Then the first half of the statement is false. But the second half is true because 254 != 255. Similarly if $1 is 255, the first half becomes true (255 != 254) but the second half becomes false.

Since you have used or logic, either half-statement being true will give an error message. With and logic, you will only get an error if both halves are true.

mangya 09-15-2016 12:01 PM

Quote:

Originally Posted by hazel (Post 5605687)
I think you need && in that first statement, not ||.

Suppose $1 is 254. Then the first half of the statement is false. But the second half is true because 254 != 255. Similarly if $1 is 255, the first half becomes true (255 != 254) but the second half becomes false.

Since you have used or logic, either half-statement being true will give an error message. With and logic, you will only get an error if both halves are true.

Hmmm... now I got it. Thanks for the explanation.


All times are GMT -5. The time now is 11:50 PM.