Languages
[Edit]
EN

Bash - check if number is less than

0 points
Created by:
Wade
562

In this article, we would like to show you how to check if number is less than another number in Bash.

Practical example

In this example, we use -lt operator to check if number is less than another number inside if statement.

script.sh file:

#!/bin/bash

number=3

if [ "$number" -lt 5 ]; then
    echo "$number is less than 5"
fi

Note: this approach should be used in POSIX shells where other solutions may not work.

Run in command line:

./script.sh

Output:

3 is less than 5

 

Altermative notation

1. test based solution

#!/bin/bash

number=3

if test "$number" -lt 5; then
    echo "$number is less than 5"
fi

Note: [ ] notation is shorthand of test command.

2. [[ ]] based solution

#!/bin/bash

number=3

if [[ "$number" -lt 5 ]]; then
    echo "$number is less than 5"
fi

Note: [[ ]] notation is like extended test command, adding additional features (e.g. regular expressions).

3. (( )) based solution

#!/bin/bash

number=3

if (( "$number" < 5 )); then
    echo "$number is less than 5"
fi

Note: (( )) notation was created to simplyfy conditions (like in C language).

 

See also

  1. Bash - compare number variable to another number

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join