Skip to content
Latchkey

bash "integer expression expected" in CI

The numeric comparison operators -eq, -ne, -lt, -gt, -le, -ge require integer operands. When a captured value is empty or non-numeric (whitespace, a version string, an error message), test reports "integer expression expected".

What this error means

A count or exit-code comparison fails with "[: <value>: integer expression expected". Often the value came from a command whose output was not a clean integer.

bash
run.sh: line 5: [: hello: integer expression expected

Common causes

A non-numeric value in a numeric test

A variable used with -eq/-gt holds text (a whole line, a version, a stray newline) instead of a plain integer.

An empty capture from a failed command

A command substitution returned nothing (the command failed or matched no lines), so the comparison runs against an empty string.

How to fix it

Compare strings with = for text

Use the string operators = and != for non-numeric values, and reserve -eq for integers only.

bash
# strings:
[ "$name" = "main" ]
# integers:
[ "$count" -gt 0 ]

Sanitize and default the value

  1. Strip surrounding whitespace from command output before comparing.
  2. Default an empty capture to 0 so the test has a valid integer.
  3. Validate that the value is numeric before the comparison.
bash
count=$(grep -c ERROR log.txt || echo 0)
count=${count:-0}
[ "$count" -gt 0 ] && echo "errors found"

How to prevent it

  • Use -eq family only for integers; =/!= for strings.
  • Default possibly-empty captures with ${var:-0}.
  • Quote operands so an empty value stays a single argument.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →