susataya.blogg.se

Bash convert string to integer for comparison
Bash convert string to integer for comparison








bash convert string to integer for comparison

bash convert string to integer for comparison

Ive tried to check if the value is numeric and if so, cast it to int but this fails whenever the value is alpha numeric. When you need some expansions to work use double quotes. One of the approaches I found so fare was to simply add a numeric value and thereby convert it. For example, 12 is said to be in between 100 and 200 because its being evaluated as a string. Rather than using a format specifier, it is also possible to use the int function. As Mark has mentioned in his answer, a simple substitution will fail in cases where there is no leading digit, such as. There are other things to keep in mind when picking quotes (like escaping some special characters - $, `, \, and ! when history expansion is enabled - on double quotes), but basically, if you want a literal string use single quotes. The d format specifier results in only the integer part of the number being printed, rounding it down. To avoid this, use a double quote around the variable name in the comparison like this: str="STRING"

Bash convert string to integer for comparison code#

That's because the code would expand to: str=""Īnd = is not a unary operator, even though it has only one parameter after it. For example, the following code would work and induce you to think it's bug free: str="STRING"īut then, if at some point you had an empty string bash would complain about expecting a unary operator. When using test to compare the value of strings, be aware that expanding an empty string without enclosing double quotes can result in syntax errors. In the example above, "$variable1" and "$variable2" will actually expand to the values contained in the variables, which will then be compared. Comparing '$variable1' and '$variable2' will result false everytime, since you will be comparing the literal strings and not the variable values.ĭouble quotes still allow some expansions to happen (check the "Quoting" section of man bash page for more details). So they are not really useful on most cases where you want to do comparisons, since usually you will want to compare variables. Single quotes basically mean you want the literal value of the string.

bash convert string to integer for comparison

Some things you want to take notice when choosing whether to use single or double quotes in comparisons: Should expansions work?










Bash convert string to integer for comparison