Read success and failure immediately
#Zero conventionally means success; nonzero means another outcome. Save $? before another command overwrites it.
Fragment
Some tools use distinct statuses for no matches and errors.
Reference
Read commands, quoting, streams, paths and scripts.
POSIX sh (2017 baseline), Bash additions and named Unix tools. Examples are independent fragments; file paths are illustrative. Bash-only syntax is labeled. macOS and Linux utility flags can differ.
POSIX sh docs test utility ↗
Zero conventionally means success; nonzero means another outcome. Save $? before another command overwrites it.
Fragment
Some tools use distinct statuses for no matches and errors.
&& runs its right side after success; || runs it after failure. ; sequences commands without requiring success.
Fragment
a && b || c also runs c if b fails; it is not a general if/else replacement.
[ is a command: spaces around its arguments matter. = compares strings, -eq compares integers, -f checks a regular file and -d checks a directory.
Fragment
Quote operands; avoid nonportable == and ambiguous compound tests in [.
for can iterate quoted arguments. IFS= read -r preserves leading spaces and backslashes; the extra condition keeps a final nonempty unterminated line.
Fragment
Line-based input is not a safe encoding of arbitrary filenames containing newlines.
case matches shell patterns, not regular expressions. ;; ends a branch.
Fragment
( commands ) runs in a subshell environment. { commands; } groups commands in the current shell.
Fragment