Reputation: 5
I'm trying to write what would seem to be a simple if statement in most languages, however in bash this doesnt seem to work at all.
When I run the script it always enters the first if statement. Can anyone offer help me as to what I am doing wrong?
PERC=.5
if [ "$PERC" > "1.00" ]
then
echo "Entered first statement"
else
if [ "$PERC" < "1.00" ]
then
echo "Entered second statement"
fi
fi
Thanks for your help.
Upvotes: 0
Views: 340
Reputation: 241758
>
and <
compare strings, not numbers (and must be backslashed or quoted in single [...]
). Use -gt
, -lt
etc. to compare numbers, or use arithmetic conditions:
if (( a < b || b <= c )) ; then
Note, however, that bash only handles integer arithmetics. To compare floats, you can use bc
:
if [[ 1 == $( bc <<< '1.5 < 1.00' ) ]] ; then
Upvotes: 2
Reputation: 780714
>
and <
are the I/O redirection operators. So
if [ "$PERC" > "1.0" ]
is executing the command [ "$PERC ]
, redirecting the output to the file 1.0
, and then if
is testing whether the command succeeded. [ "$PERC" ]
simply tests whether "$PERC"
is a non-empty string.
To use them as operators in the test
command, you need to quote or escape them:
if [ "$PERC" '>' "1.0" ]
You could also use bash's [[
conditional syntax instead of the [
command:
if [[ $PERC > "1.0" ]]
Upvotes: 2