Integer and file tests
Use -eq, -ne, -lt, -le, -gt, and -ge for integer equality, inequality, less than, less than or equal, greater than, and greater than or equal. Use [ "$count" -ge 5 ] with known valid integer operands. For Bash builtin [ ], a well-formed false integer comparison returns 1, but a malformed integer operand can return 2 with a diagnostic. These numeric comparisons accept decimal integers such as 08; arithmetic contexts in later chapters have different rules. Validate user text and range before numeric evaluation (regex validation is introduced later in this chapter). File tests include -e for existence, -f for a regular file, -d for a directory, -s for nonzero size, -r, -w, -x for access checks, and -L for symbolic links. Most file tests follow symbolic links; -L checks the link itself. A dangling symbolic link can satisfy -L while failing -e, because its target does not exist. A permission test is only a snapshot, not a guarantee that a later operation will succeed. Run file examples in a new empty directory.
Practical examples
Run each example separately in Bash 5.2 in a fresh empty practice directory. Tests use default shell options and C locale. Output is shown separately; do not enter it as code.
Compare counts
Expected stdout:
enough12 is numerically at least 10.
Check a regular file
printf '%s\n' report > 'daily report.txt'if [ -f 'daily report.txt' ]; then printf '%s\n' file; fiif [ -d . ]; then printf '%s\n' directory; fiExpected stdout:
filedirectoryA regular file and a directory satisfy different predicates.
Check content size
: > empty.txtprintf '%s\n' data > data.txt[ -s empty.txt ]; printf '%s\n' "$?"[ -s data.txt ]; printf '%s\n' "$?"Expected stdout:
10The colon builtin does nothing successfully; redirection creates an empty file. Only data.txt has nonzero size.
Common mistakes
Do not use > as an unquoted numeric comparison in [ ]: it can be parsed as redirection. Use -gt. Check the status of the actual file operation even after a successful file test.
Practice
Create an empty file and a file containing a line. Test regular-file and nonempty-file properties. Compare 12 and 15 with -lt.
Next: AND, OR and negation