Exit Codes, if, [[ ]] & case

How Bash decides true and false, tests on strings, numbers and files, regex matching and case.

In Bash, 'true' and 'false' are exit statuses: every command returns 0 for success and a non-zero number for failure, and if simply runs a command and checks that number. [[ ... ]] is a command whose only job is to test something.

Decisions

$? holds the exit status of the last command: grep returns 0 when it finds a match, 1 when it does not.

if grep -q ...; then branches directly on grep's status (-q suppresses the output).

-gt, -lt, -eq compare numbers; == compares strings and allows patterns like rev_*.

-f tests for a regular file, -d for a directory; && and || run the next command only on success / failure.

=~ matches a regular expression; the captured groups land in BASH_REMATCH.

Test operators

if [[ $count > 9 ]]; then if [[ $count -gt 9 ]]; then # or (( count > 9))

> inside [[ ]] compares strings alphabetically, so "10" > "9" is false. Use -gt or (( )) for numbers.

What exit status means success?

0. Any non-zero value (1-255) means failure, and different values can signal different errors.

How do you run a command only if the previous one failed?