Fundamentals 4 min read

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.

ITPUB
ITPUB
ITPUB
Mastering Shell Test Expressions: test vs [] with Real‑World 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ShellBashConditionalstest
ITPUB
Written by

ITPUB

Official ITPUB account sharing technical insights, community news, and exciting events.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.