← Lessons/Conditionals & Tests
← Conditionals & Tests

Negate a test

Learn

Negating a test

! flips any test: [ ! -d logs ] is true when the directory does not exist.

Always double-quote variables inside a test: [ -z "$x" ], not [ -z $x ]. If $x is empty and unquoted, it vanishes entirely and the test becomes malformed. The quotes hold its place.

Deciding without if. Every command reports whether it succeeded, and you can branch on that directly with && ("and then, if it worked") and || ("or else, if it failed"):

mkdir build && echo "made it"    # echo runs only if mkdir succeeded
test -f x.txt || echo "missing"  # echo runs only if the test failed

For a quick one-liner this reads beautifully; for anything with several steps, use a full if. The editor opens with your script from the previous step.

There is no secret.key here. Print no secret found only when it's absent — negate the test with !.

Interview prep

File/empty tests are the backbone of safe scripts.

Why guard with [ -f config ] before reading a file in a script?

So the script fails gracefully instead of erroring (or worse, acting on missing data). Defensive checks — file exists, variable non-empty, previous command succeeded — are what separates a throwaway snippet from a script you'd run in CI.

$ bash solution.sh
Loading...

Output

Run your solution to see its output here.