'What does '-gt' operator mean in Bash programming?

I was reading some code, but I could not understand one thing.

What does -gt mean in the following code?

if [ $result -gt 0 ] ;
then
    exit 1 ;
fi


Solution 1:[1]

It's an arithmetic test. help test tells:

  arg1 OP arg2   Arithmetic tests.  OP is one of -eq, -ne,
                 -lt, -le, -gt, or -ge.

-gt is greater than.

In your example, the condition is true if the variable result is greater than zero.

Solution 2:[2]

In Bash, there are no variable types as you would find in C or Java.

Imagine if I have the following pseudo-program:

foo = 23
bar = 149
if ( $foo > $bar ) then
    say "Foo is bigger than bar"
elseif ( $bar > $foo ) then
    say "Bar is greater than foo"
else
    say "Bar and foo must be equal"
endif

What should this program do?

Well, it depends if foo and bar are strings or numbers. If foo and bar are Inventory IDs that just happen to contain nothing but digits, I probably want to say that bar is less than foo because (if you do string comparison) the "1" is less than "2".

However, if foo and bar are numeric, I would want to say that bar is greater than foo because 23 is numerically less than 149.

The only way for Bash to know if I should do a numeric or string comparison of the number is to have two separate boolean operators for strings vs. numbers.

For example: Foo and bar are numbers, I'll use the numeric comparisons:

foo=23
bar=149
if [[ $foo -gt $bar ]]
then
    echo "Foo is greater than bar."
elif [[ $bar -gt $foo ]]
    echo "Bar is greater than foo."
else
    echo "Bar and foo are equal."
fi

And I'll get the results:

Bar is greater than foo.

If foo and bar are strings, I'll use the string comparisons:

foo=23
bar=149
if [[ $foo > $bar ]]
then
    echo "Foo is greater than bar."
elif [[ $bar > $foo ]]
    echo "Bar is greater than foo."
else
    echo "Bar and foo are equal."
fi

And I'll get:

Foo is greater than bar.

Take a look at the manpage for Bash under CONDITIONAL EXPRESSIONS to see all of the boolean expressions for both strings and numeric values.

Solution 3:[3]

This is the 'greater than' comparator for integers variables. So the code translates to this in pseudocode: if($result > 0) ...

Here is a good reference for Bash comparators. The most important thing about them is remembering which are used for strings and which for integers:

Linux Bash - Comparison Operators

Solution 4:[4]

This means:

 greater than

Or

 >

Solution 5:[5]

-gt means "is greater than"

So, if [ $result -gt 0 ] means "if $result is greater than 0."

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 devnull
Solution 2 Peter Mortensen
Solution 3 Peter Mortensen
Solution 4 oz123
Solution 5 elixenide