File Tests (-f -d -e)
In this page:
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: -e checks "exists at all"; -f and -d are 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
🔒
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: