File Tests (-f -d -e)
File tests are like peeking through the window to see if a house is there, and whether it is a house or a garden. You can ask if something exists, is a file, or is a folder.
In this page:
Syntax
[[ -f path ]]
[[ -d path ]]
[[ -e path ]]
File Tests (-f -d -e)
[[ -f path ]] tests whether a path exists and is a regular file, [[ -d path ]] tests for a directory, and [[ -e path ]] tests for existence of either.
These conditional file tests are essential before reading, writing, or acting on a path you're not certain exists. Combine them with ! to test the opposite, like [[ ! -f path ]].
Note:
-echecks "exists at all"-fand-dare more specific about what kind of thing it is.
Example: File Tests (-f -d -e)
#!/bin/bash
touch sample.txt
mkdir -p sample_dir
if [[ -f sample.txt ]]; then
echo "sample.txt is a regular file"
fi
if [[ -d sample_dir ]]; then
echo "sample_dir is a directory"
fi
if [[ -e nonexistent.txt ]]; then
echo "This won't print"
else
echo "nonexistent.txt does not exist"
fi
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting spaces in
[ -f "$file" ]. - Using
-ewhen you need-for-d, since-eis true for any type. - Leaving the variable unquoted, which fails with names that have spaces.
🔒
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: