Test Files and Directories in Bash

Guard script actions with file existence and permission checks.

macOSbashshellscriptingLow risk
Use [ -f file ], [ -d dir ] and [ -r file ] to test type and readability before acting.

01Command

Command
$ [ -f config.yml ] && [ -r config.yml ] && echo "readable config"

02What it does

Shell test operators let a script verify preconditions cheaply: a file exists, a directory is writable, a path is a symlink. That prevents confusing downstream errors and is a habit that makes automation trustworthy.

03Risk

RiskLow risk
RequirementsmacOS default zsh/bash (bash 3.2+; some features need bash 4+ via Homebrew)
CompatibilitymacOS with bash 3.2+ (GNU bash 4+ via Homebrew for advanced features)
!Warning: There is a race between the test and the action; for critical code, open the file and handle errors instead.

04Undo

✓No undo needed — this command does not change persistent state.

05Sources

Last verified: 2026-10-13 · Category: Developer