FIELD NOTES / UNIX & LINUXNew tools on weekdays. Beyond the man page.
$test

test: turn observations into shell decisions

Read brackets as a command, preserve its arguments, distinguish false from error, and know when a filesystem check cannot make the next operation safe.

THE DEEP DIVE16 MIN READ
01

Start with status, not printed output

test evaluates one conditional expression and normally prints nothing. Its useful result is an exit status: 0 means true and 1 means false. The shell's if, &&, and || syntax makes decisions from that status.

Work in a directory where you may create test-demo. mkdir creates it, && runs the next command only after success, and cd enters it. The second mkdir creates the config directory that we will inspect.

[ is a command name, not grouping punctuation. -d is a unary predicate: it consumes one pathname and is true when that pathname resolves to a directory. The closing ] is the final argument required by the [ form. Spaces keep [, -d, config, and ] as four separate shell words. Because the predicate is true, the shell runs printf after &&. The printf article explains why the fixed format and data argument are separate.

TERMINALCommand — disposable fixture and first predicate
mkdir test-demo &&
cd test-demo &&
mkdir config &&
[ -d config ] && printf '%s\n' 'config is a directory'
TERMINALOutput
config is a directory

This article executes Bash 5.2.37 builtins and GNU Coreutils 9.7 external test on Debian. POSIX defines the portable core; other shells and standalone utilities can add predicates or differ at extensions.

02

Keep false separate from an evaluation error

A false condition is ordinary control flow. An invalid expression is different. The first test asks whether missing is a regular file with -f; it returns 1. The second uses env to bypass Bash's builtin and invoke the external GNU utility. -eq requests an integer equality comparison, but nope is not an integer, so GNU test diagnoses the expression and returns 2.

Each printf receives the status from the command immediately before it. $? is a shell parameter that expands to that status. Standard error from the invalid expression remains visible before the recorded status.

Do not reduce every nonzero result to false when malformed input or an unsupported expression must stop a script. Capture the status and distinguish 1 from values greater than 1 when the condition comes from data or a constructed expression.

TERMINALCommand — false, then invalid
test -f missing
printf 'missing status=%s\n' "$?"
env test nope -eq 3
printf 'invalid status=%s\n' "$?"
TERMINALOutput — diagnostic wording is implementation-dependent
missing status=1
test: invalid integer 'nope'
invalid status=2

GNU documents status 2 for an error. A shell builtin can use another nonzero error status, so portable control flow should treat greater than 1 as an error class rather than depend on one exact value.

03

Quote expansions so one value stays one argument

test recognizes expressions from the arguments it receives. Unquoted shell expansion can remove an empty operand or split one value into several operands before test runs. Double quotes preserve the expansion as exactly one argument.

-n is true when its following string has nonzero length; -z is true when the string has zero length. The variable empty contains no characters, while label contains a space. Quoting lets both predicates receive the intended single operand.

The compact-looking form [-n "$label"] is not equivalent: without spaces, the shell looks for a command whose name begins with [-n. Treat the brackets as ordinary command tokens and quote every expansion that must remain one operand.

TERMINALCommand
empty=
label='release candidate'
[ -z "$empty" ] && printf '%s\n' 'empty is empty'
[ -n "$label" ] && printf 'label=%s\n' "$label"
TERMINALOutput
empty is empty
label=release candidate

Inside Bash's separate [[ ... ]] compound command, word splitting and pathname expansion follow different rules. That does not make unquoted expansions safe in portable test or [ expressions.

04

Choose string or integer semantics explicitly

The = binary operator compares two strings. The -eq operator compares two integers. They answer different questions even when the operands contain digits.

As strings, 08 and 8 differ because the first has a leading zero. As integers accepted by GNU test and Bash test, they have equal numeric values. The shell's && joins two commands and runs printf only when the preceding predicate returns 0.

Use -ne, -lt, -le, -gt, and -ge for integer not-equal and ordering comparisons. Validate data that might not be an integer before using those operators; an invalid operand is an error, not a useful false answer.

TERMINALCommand
[ 08 = 8 ] || printf '%s\n' 'different strings'
[ 08 -eq 8 ] && printf '%s\n' 'equal integers'
TERMINALOutput
different strings
equal integers

For POSIX portability use = with test. == is accepted by Bash and GNU but is not the portable spelling.

05

Ask what a pathname resolves to

Most file predicates follow a symbolic link and inspect its target. -f is true for a resolved regular file, -d for a resolved directory, and -e when the resolved pathname exists. -L, also spelled -h by common implementations, inspects the directory entry itself and is true for a symbolic link.

The shell's > redirection creates payload, replacing its contents if that pathname already exists, before printf runs. ln -s creates good-link pointing to it and broken-link pointing to a nonexistent target. good-link is both a link and, after resolution, a regular file. broken-link is still a link, but -e is false because its target does not exist.

This distinction matters during cleanup and incident review: testing only -e silently misses dangling links. Use -L when the link object is the fact you need.

TERMINALCommand
printf '%s\n' data > payload
ln -s payload good-link
ln -s absent broken-link
[ -L good-link ] && [ -f good-link ] && printf '%s\n' 'good-link: link to regular file'
[ -L broken-link ] && [ ! -e broken-link ] && printf '%s\n' 'broken-link: dangling link'
TERMINALOutput
good-link: link to regular file
broken-link: dangling link

! is a separate argument that negates the following test expression. Here it turns the false -e result into a true condition.

06

Compare identity and freshness without reading content

Two pathnames can name the same underlying file. The -ef binary predicate is true when both operands have the same device and inode numbers. ln without -s creates hard-copy as a hard link to payload, so -ef reports one file identity rather than merely equal bytes.

The -nt predicate asks whether the left operand's modification time is newer than the right operand's. sleep 1 ensures the subsequently created marker has a later timestamp on filesystems with at least one-second resolution.

These are snapshot observations. Another process can replace a pathname after test returns. Use them for reporting and dependency decisions, not as a lock or authorization boundary.

TERMINALCommand
ln payload hard-copy
[ payload -ef hard-copy ] && printf '%s\n' 'same file identity'
sleep 1
printf '%s\n' done > marker
[ marker -nt payload ] && printf '%s\n' 'marker is newer'
TERMINALOutput
same file identity
marker is newer

-ef and -nt are widely available GNU, Bash, and BSD extensions, but they are not in the portable POSIX test expression set.

07

Let the shell compose independent predicates

Historical test expressions use -a for AND and -o for OR. POSIX marks forms with more than four arguments as unspecified, and GNU warns that expansions can make the expression ambiguous. Prefer separate test commands joined by shell control operators.

The first [ command checks that payload is a regular file. Only if it succeeds does shell && run the second predicate, which checks that the file has nonzero size with -s. A second && prints the result. Each predicate keeps a simple, unambiguous argument shape.

For OR, join complete predicates with shell ||. Use braces or an if statement when several commands belong to one branch; do not rely on a clever chain whose && and || grouping a future reader must reconstruct.

TERMINALCommand
[ -f payload ] && [ -s payload ] &&
  printf '%s\n' 'payload is a nonempty regular file'
TERMINALOutput
payload is a nonempty regular file

The newline after && is valid shell syntax because the operator announces that another command must follow.

08

Expect old parsers to disagree at ambiguous boundaries

The three-token expression test -a -a -a exposes why argument-count parsing and the historical -a connective are a poor combination. The same words reach three implementations here, but their older parsers do not agree.

LC_ALL=C asks the external GNU command for a stable English diagnostic. env bypasses Bash's builtin; installed GNU Coreutils 9.7 treats the expression as an error and returns 2. The unadorned test uses Bash 5.2.37's builtin and returns 0. dash -c starts Dash, asks its builtin to evaluate the quoted command string, and also returns 0. Each printf captures the immediately preceding status.

GNU Coreutils 9.12, released September 14, 2026, documents a fix for this exact case: -a and -o are no longer interpreted as connectives when they occupy operands of a binary expression, so current external GNU test agrees with the true result. That is a parsing-correctness fix, not a documented vulnerability or evidence of exploitation. Do not write new expressions that depend on either result; keep each predicate simple and combine complete commands with shell && or ||.

TERMINALCommand — controlled historical parser comparison
LC_ALL=C env test -a -a -a
printf 'external GNU 9.7 status=%s\n' "$?"
test -a -a -a
printf 'Bash 5.2.37 builtin status=%s\n' "$?"
dash -c 'test -a -a -a'
printf 'Dash builtin status=%s\n' "$?"
TERMINALObserved output on the stated environment
test: '-a': unary operator expected
external GNU 9.7 status=2
Bash 5.2.37 builtin status=0
Dash builtin status=0

GNU 9.12 was not installed in the execution environment. Its corrected result is source-verified from the upstream 9.12 release announcement, not presented as locally executed output.

09

Inventory link and privilege-bearing entries

During an authorized review of a supplied directory, test can classify entries before deeper inspection. -L identifies links, -u identifies files with the set-user-ID bit, and -g identifies files with the set-group-ID bit.

The loop visits each pathname matched by review/*. for assigns one pathname to path per iteration. The shell expands the glob before the loop; the fixture guarantees matches. Each quoted $path remains one argument. The two lines beginning #! and exit make helper a harmless synthetic script-like file; the article never executes it. chmod u+s adds the set-user-ID bit, and chmod g+s adds the set-group-ID bit.

A set-ID bit is a fact, not proof of a vulnerability, and many systems ignore it on scripts or on filesystems mounted nosuid. A symbolic link is equally not malicious by itself. Use this pass to build a review list, then inspect ownership, target, mount policy, and the actual executable behavior.

TERMINALCommand — synthetic review directory
mkdir review
printf '#!/bin/sh\nexit 0\n' > review/helper
chmod u+s review/helper
printf '%s\n' data > review/shared
chmod g+s review/shared
ln -s /etc/passwd review/account-link
for path in review/*; do
  [ -L "$path" ] && printf 'link %s -> %s\n' "$path" "$(readlink "$path")"
  [ -u "$path" ] && printf 'setuid %s\n' "$path"
  [ -g "$path" ] && printf 'setgid %s\n' "$path"
done
TERMINALOutput
link review/account-link -> /etc/passwd
setuid review/helper
setgid review/shared

$(...) is shell command substitution: the shell runs readlink and inserts its output as one quoted printf argument. Do not execute an unfamiliar set-ID binary merely to investigate it.

10

Do not pre-test a pathname you need to claim

A check-then-act sequence such as [ ! -e work.lock ] followed by creating work.lock has a time-of-check-to-time-of-use race. Another process can create or replace the pathname between the two operations. test cannot reserve the fact it observed.

Ask the state-changing operation to decide instead. mkdir creates lockdir only if that pathname does not already exist. The if statement branches directly on mkdir's status. Standard error is redirected to /dev/null because the else branch supplies the expected busy message. trap registers cleanup when this shell exits.

This is a small local lock pattern, not a distributed lock service. It assumes cooperating participants and a parent directory protected from hostile writes. A peer that may remove or rename entries in that parent can delete or replace the lock after acquisition; use an operating-system locking primitive or service suited to that threat model. The owning process must also handle stale directories and place the lock on a filesystem whose mkdir semantics fit the coordination scope. The lesson is broader: when correctness depends on claiming a name, prefer an atomic create primitive over a preceding observation.

TERMINALCommand — atomic local claim
lockdir=work.lock
if mkdir "$lockdir" 2>/dev/null; then
  trap 'rmdir "$lockdir"' EXIT
  printf '%s\n' 'lock acquired'
else
  printf '%s\n' 'lock busy'
fi
TERMINALOutput
lock acquired

The shell performs 2>/dev/null before mkdir runs: file descriptor 2 is standard error. The trap action uses single quotes so $lockdir expands when the trap runs, not when it is registered.

11

Detect whether output is attached to a terminal

-t takes a file descriptor number and is true when that descriptor is open on a terminal. Descriptor 1 is standard output. Programs use this fact to decide whether interactive decoration is appropriate.

The opening ( and closing ) ask the shell to run the enclosed commands in a subshell. The following > captured.txt redirection applies to that whole parenthesized group. It makes the subshell's descriptor 1 a regular file, so the else branch writes plain. cat then displays the file on the outer command's standard output.

Terminal detection is a presentation hint, not a trust decision. A terminal can record output, and a pipe can ultimately feed a human. Keep color and control sequences opt-in or overridable when logs and automation matter.

TERMINALCommand
(
  if [ -t 1 ]; then
    printf '%s\n' decorated
  else
    printf '%s\n' plain
  fi
) > captured.txt
cat captured.txt
TERMINALOutput
plain

When pasted into an interactive terminal without the outer redirection, [ -t 1 ] is normally true. The fixed transcript deliberately makes the result reproducible.

12

State which conditional language you are using

In many shells, test and [ are builtins even when /usr/bin/test also exists. command -V test reveals what an unadorned invocation selects; env test can select the external utility for implementation-specific verification. Do not assume the builtin and external program have identical extensions or diagnostics.

Bash's [[ ... ]] is a compound command with different parsing, pattern matching, quoting, and numeric rules. It is often a better choice in a Bash-only script, but it is not a drop-in spelling for portable [ ... ]. Choose one language intentionally and document the shell contract.

test is best at answering a narrow question about the state visible now. Preserve its operands, handle false separately from error, compose simple predicates in the shell, and let atomic operations—not preflight checks—enforce claims that must survive the next instruction.

No specific vulnerability in test itself is claimed here. The security-relevant boundaries are ambiguous argument construction, current-state file inspection, special-mode and link triage, and misuse of a non-atomic observation as authorization or locking.

Back to latest issue
HELP SHAPE THE NEXT ISSUE

What belongs in your toolbox?

Choose a command you want to know better. We start with familiar tools and work toward the less obvious ones.

READER’S CHOICE

What should we cover next?

Vote for a future deep dive, or suggest a command we missed.

One command name, up to 32 characters. Suggestions are reviewed by a person. A new article starts a fresh poll.

Loading poll…