Bash

πŸ›  Bash Test Operator Cheat Sheet

πŸ”€ String Comparisons

OperatorMeaningExample
= / ==Strings are equal[[ $a == "yes" ]]
!=Strings are NOT equal[[ $a != "no" ]]
=~Left side matches regex on right[[ $name =~ ^[A-Z] ]]
< / >Lexicographic (alphabetical) compare[[ $a < $b ]]

πŸ”’ Integer Comparisons

(Use - style operators for numbers)

OperatorMeaningExample
-eqequal to[ $x -eq 5 ]
-nenot equal to[ $x -ne 10 ]
-ltless than[ $x -lt 3 ]
-leless than or equal to[ $x -le 7 ]
-gtgreater than[ $x -gt 100 ]
-gegreater than or equal to[ $x -ge 18 ]

πŸ“‚ File Tests

OperatorMeaningExample
-efile exists[ -e /path/file ]
-fregular file[ -f myfile.txt ]
-ddirectory exists[ -d /etc ]
-rfile is readable[ -r secret.txt ]
-wfile is writable[ -w /tmp/file ]
-xfile is executable[ -x script.sh ]

πŸŒ€ Regex Examples with =~

PatternMatchesDoesn’t Match
^[A-Z]"Hello", "Zebra""apple", "1start"
^[0-9]+$"123", "007""12a", "abc"
foo|bar"foo", "barbecue""baz"
^[a-z]{3}$"cat", "dog""cats", "do"
\.(jpg|png)$"file.jpg", "img.png""pic.jpeg", "file.JPG"

πŸ’‘ Pro Tips

  • Prefer [[ ... ]] over [ ... ] β€” it’s safer and supports =~ regex matching.
  • Don’t quote the regex pattern on the right side of =~ β€” quoting forces a literal match.
  • Prefix a test with ! to invert it (logical NOT).
  • Combine tests with && (AND) and || (OR) for complex conditions.