Test Files and Directories in Bash
Guard script actions with file existence and permission checks.
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
!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
- bash.1.en.html manual pageEvidence: The bash manual page documents test operators.
Last verified: 2026-10-13 · Category: Developer