First of all, sh
doesn't handle (( … ))
. You could use bash
, but even then it's only for numeric integer expressions. See later in this answer for sh
-compatible use of awk
. I note that you describe your script as a bash
script but you've used #!/bin/sh
as the header. This header declares the script as a sh
script, which has slightly different syntax.
If you're using bash
you should search the documentation (man bash
) for ((
(you might need to escape the brackets, i.e. \(\(
, if your pager requires it). You'll find this text,
((expression))
The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION.
Search down for ARITHMETIC EVALUATION
and you'll eventually read this (my emphasis),
ARITHMETIC EVALUATION The shell allows arithmetic expressions to be evaluated, under certain circumstances (see the let
and declare
builtin commands, the ((
compound command, and Arithmetic Expansion). Evaluation is done in fixed-width integers with no check for overflow [...]
What this is telling you is that the (( … ))
construct can evaluate integer arithmetic. It's not for strings or for floating point arithmetic.
Continuing now with an answer for either sh
or bash
.
You can handle strings with [ … ]
or [[ … ]]
,
if [[ "$str1" == "$str2" ]] … # bash
or
if [ "$str1" = "$str2" ] … # POSIX including sh, and bash
Floating point arithmetic is harder; you have to drop out to bc
or awk
for this (my preferred approach is awk
):
a=12.34 b=5.678 # These are strings
You cannot compare them as integers, because they're floats
if [[ "$a" -gt "$b" ]]; then echo yes; else echo no; fi
-bash: [[: 12.34: syntax error: invalid arithmetic operator (error token is ".34")
You can use awk though
if awk -v a="$a" -v b="$b" 'BEGIN { exit !(a > b) }'; then echo yes; else echo no; fi
yes
Here, we assign two awk
variables a
and b
. Before awk
has a chance to start reading from stdin we compare them numerically with >
and exit with a status that corresponds to true
/false
. That awk
exit status is processed by the shell's if … then … else … fi
construct as usual.