Serious Shell Programming
  • Introduction
  • Acknowledgements
  • Basics
    • Strings
      • Single-Quotes
      • Double-Quotes
      • Unquoted Strings
      • Compound Strings
    • Here Documents
      • Here Doc
      • Indented Here Doc
      • Literal Here Doc
      • In-Memory Here Doc
    • Conditionals
      • Built-in test
      • Parameter Conditionals
      • Parameter test
    • Regex
      • grep
      • awk
      • pcre
    • Control Flow
      • Binary Operators
      • if-elif-else
      • case Statement
      • for Loop
      • while Loop
      • Functions
  • shellcheck
    • Introduction
    • Bad Advice
  • Style
    • awk
    • case
    • Redirection
    • Comments
    • trap
  • String Functions
    • substr
    • sprintf
    • replace
    • replaceall
    • replacestart
    • replaceend
    • fnmatch
  • awk
    • Pre-declaring Arrays
    • Sorting Arrays
  • Know Your limits
    • Arguments
    • Environment Variables
    • Solutions
Powered by GitBook
On this page

Was this helpful?

  1. Basics
  2. Conditionals

Built-in test

The [ built-in takes a series of arguments to perform one or more tests and return an exit status of zero (success) or non-zero (failure). Multiple expressions are separated by one or more -a (AND) or -o (OR) operators and can be grouped using parentheses (parentheses must be escaped or quoted to prevent interpolation).

Tests are separated into unary, binary, and string operators depending on number of operands.

Unary operators requiring a single operand include:

Operator(s)

Description

! expression

True if expression is false

-[bcdefghkprsuwxGLOS] file

Various checks against a single file/directory

-[nz] string

Test if a string is empty (-z) or non-empty (-n)

-t file_descriptor

True if file descriptor is open and to a terminal

Binary operators requiring two operands include:

Operator(s)

Description

file1 { -nt, -ot, -ef } file2

Various checks involving two files/directories

string1 { =, !=, <, > } string2

Various checks involving two strings

number1 { -eq, -ne, -gt, -ge, -lt, -le } number2

Various checks involving two numbers

When given an argument with no operator or when an operator is given zero operands, it is treated as a string and the exit status is zero (success) if the string is non-empty and non-zero (failure) otherwise.

The behavior of being given only string is the same as if given -n string. Combined with the unary NOT operator, ! string is the same as -z string.

Given the alphabet soup of unary operators, it is suggested that the readability of code is improved by using string and ! string instead of -n string and -z string, respectively.

PreviousConditionalsNextParameter Conditionals

Last updated 5 years ago

Was this helpful?