File Test Operators
Checking Existence
-e path is true if anything exists at that path at all (file, directory, symlink, etc). -f path narrows that down to "exists and is a regular file".
Example: Checking Existence
#!/bin/bash
touch sample.txt
if [[ -e sample.txt ]]; then
echo "sample.txt exists"
fi
if [[ -f sample.txt ]]; then
echo "sample.txt is a regular file"
fi
rm -f sample.txt
Login to try C/C++/Java/PHP code in the editor
Checking Directories
-d path is true only when the path exists and is a directory. This is the standard guard before cd-ing into a path or listing its contents.
Example: Checking Directories
#!/bin/bash
mkdir -p sample_dir
if [[ -d sample_dir ]]; then
echo "sample_dir is a directory"
fi
if [[ ! -d does_not_exist ]]; then
echo "does_not_exist is not a directory"
fi
rmdir sample_dir
Login to try C/C++/Java/PHP code in the editor
Checking Permissions
-r, -w, and -x check whether the current user has read, write, or execute permission on a path, respectively. These reflect actual OS-level permission checks, not just the file's mode bits.
Example: Checking Permissions
#!/bin/bash
touch perm_test.txt
chmod 644 perm_test.txt
if [[ -r perm_test.txt ]]; then
echo "readable"
fi
if [[ -w perm_test.txt ]]; then
echo "writable"
fi
if [[ ! -x perm_test.txt ]]; then
echo "not executable"
fi
rm -f perm_test.txt
Login to try C/C++/Java/PHP code in the editor
Checking File Size
-s path is true when the path exists and its size is greater than zero bytes, which is a quick way to detect empty files before processing them.
Note: Combine tests with && or [[ -f a && -r a ]] to check several conditions at once.
Example: Checking File Size
#!/bin/bash
touch empty.txt
echo "has content" > full.txt
if [[ ! -s empty.txt ]]; then
echo "empty.txt is empty"
fi
if [[ -s full.txt ]]; then
echo "full.txt has content"
fi
rm -f empty.txt full.txt
Login to try C/C++/Java/PHP code in the editor
- Using
-fto check "does this path exist" when it actually only means "exists and is a regular file"; a directory fails-f. - Forgetting to quote the variable inside
[ -f $var ], which breaks if the path contains spaces or is empty. - Assuming
-wand-xreflect the current user's actual effective permissions perfectly in every edge case (e.g. read-only filesystems), when they can occasionally be misleading.
-etests existence of any kind;-ftests a regular file;-dtests a directory.-r,-w,-xtest read, write, and execute permission for the current user.-stests that a file exists and has a size greater than zero.- Prefer
[[ ... ]]over[ ... ]in bash scripts; it handles unquoted variables and empty strings more safely.
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: