Mastering Shell Test Expressions: test vs [] with Real‑World Examples
This guide explains how to use the shell test command and the [ ] syntax for file existence checks, interprets the special $? return code, demonstrates logical operators && and ||, and highlights spacing rules and additional test flags with clear examples.
In shell scripting, conditional expressions are frequently needed. Two common forms are the test command and the bracket syntax [ ]. Both evaluate expressions and set an exit status that can be inspected via the special variable $?.
Example 1: Using test
Command: # test -e /tmp/a.txt ; echo $? The output is 0, indicating success because the file /tmp/a.txt exists. In shell, an exit status of 0 means true, while any non‑zero value means false.
Logical Operators
Shell also supports the logical operators && (AND) and || (OR), analogous to other programming languages.
Example 2: # test -e /tmp/a.txt && echo 'Yes' || echo 'No' If the file exists, the command prints Yes; otherwise it prints No.
Example 3: Using Brackets [ ]
Bracket syntax requires spaces around the brackets and the expression: # [ -e /tmp/a.txt ] ; echo $? This also returns 0 when the file exists. Remember to keep a space after the opening [ and before the closing ].
Other Test Flags
The test command supports many flags (e.g., -f for regular files, -d for directories). A reference table is shown below (excerpt from “鸟哥的Linux私房菜”).
These flags allow more precise checks, such as testing file types, permissions, string comparisons, and numeric comparisons.
Understanding the correct syntax, exit status semantics, and logical operators enables reliable conditional logic in shell scripts.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
