V
V
Vladislav2015-11-19 02:00:58
linux
Vladislav, 2015-11-19 02:00:58

How to compare 2 numbers in bash?

i can compare 2 numbers like:
if [ $a -eq $b ]
but why do i get all sorts of errors if i want something like this if (a+1 == b)
if [ $(($a+ 1 )) -eq $b]
if [ $a + 1-eq $b ]
if ["$a" + 1 -eq $b]
how does it even work

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nathanael, 2015-11-19
@Div100

To perform arithmetic operations, you can use the let statement (built into bash):

$ let "a=2+2"
$ echo $a
4

For comparison, use the operator (( :
$ if (( $a > 2 )); then echo "Bigger"; else echo "smaller"; fi
Bigger

Read the imperishable Advanced Bash scripting guide (in Russian).
Another example:
$ if (( $a+2 > 6 )); then echo "Bigger"; else echo "smaller or equal"; fi
smaller or equal

Also, in expressions, you should always make sure that before and before an operator like [[ or (( there was a space in the words, otherwise bash will treat them as other tokens (merged with the previous word, for example, as a call to other commands).
We can say that the operators [, [ [ are analogues of the test command, and (( is a synonym for let or the expr utility.

A
abcd0x00, 2015-11-19
@abcd0x00

[[email protected] ~]$ a=1
[[email protected] ~]$ b=2
[[email protected] ~]$ c=3
[[email protected] ~]$ 
[[email protected] ~]$ [ $((a + b)) -eq $c ]
[[email protected] ~]$ echo $?
0
[[email protected] ~]$ [ $((a + b)) -lt $c ]
[[email protected] ~]$ echo $?
1
[[email protected] ~]$ [ $((a + b - 1)) -lt $c ]
[[email protected] ~]$ echo $?
0
[[email protected] ~]$ [ $((a + b)) -gt $c ]
[[email protected] ~]$ echo $?
1
[[email protected] ~]$ [ $((a + b + 1)) -gt $c ]
[[email protected] ~]$ echo $?
0
[[email protected] ~]$

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question