Multiple string variable comparisons in an if statement in bash
I have a number of variables that I need to verify that they match.
I have two databases of usernames, passwords, and speed packages. The database types are not the same. I need to make sure that everything is the same.
I've been searching all morning but can't get the right combination of an if statement comparing multiple variables to other variables, etc. Tried different combinations of , [], quotes, no quotes, -a, =, ==, etc. I'll either get that they all report OK when some are not, or I get that they're all bad when some are good. Or, I get a syntax error, usually with -a as the operator.
What's the proper way to compare 3 pairs of variables to make sure they match exactly.
The following works for me
As long as you're using bash, and comparing text strings, the [[..]] test is safer and more flexible. You can use && and || inside them for and/or operators.
If you're comparing integers, however, you should use ((..)) instead.
Another option, and perhaps safer, more portable, and more readable in the long run, would be to simply use separate nested if statements.
Finally, remember, QUOTE ALL OF YOUR VARIABLE SUBSTITUTIONS. You should never leave the quotes off a parameter expansion unless you explicitly want the resulting string to be word-split by the shell (globbing patterns are also expanded). This is a vitally important concept in scripting, so train yourself to do it correctly now. You can learn about the exceptions later.
This is particularly important when using the old "[" single-bracket test command.
(And actually, one of the benefits of "[[" is that it's one of the exceptions where quotes aren't needed, at least on the left hand side. The right hand side, however, does exhibit differing effects when using "==" and "=~". See the links I gave above for more.)
|All times are GMT -5. The time now is 03:44 AM.|