Check if a value is an integer

is_int() { [[ $1 =~ ^[0-9]+$ ]]; }

September 17, 2023bashoneliners

Explanation

The one-liner defines an is_int function that can be used to check if some value or variable is a valid Bash integer.

The single command [[ $1 =~ ^[0-9]+$ ]] in the function exits with success when the function parameter $1 matches the regular expression ^[0-9]+$, that is, it contains only digits from start (^) until the end ($).

Examples:

is_int 123  # success
is_int 0123  # success
a="123"; is_int "$a"  # success
is_int foo  # fail
is_int " 123"  # fail
is_int 123.0  # fail
is_int 123f  # fail
is_int 0x33  # fail
is_int ""  # fail

Note that the exit code of the last command executed in a function becomes the exit code of the function itself, so we don't need explicit return statements, the single [[ ... ]] is enough, we let its result bubble up.

When defining a function on the command line like this, it's important to terminate the function definition with ; } as in this example: the semicolon and the space are both required for the syntax to be valid.

Functions are best to keep in script files, spelled out across multiple lines, more like this:

is_int() {
  [[ $1 =~ ^[0-9]+$ ]]
}