Shell Script to Check if a File Exists
9月 20, 2025
To check if a file exists in a shell script, you can use the test command or the [ command. Both commands are equivalent, but the test command is more powerful and allows you to perform more complex checks.
Here’s an example using the test command:
if test -e {filename}; then
echo "File exists"
else
echo "File does not exist"
fiAlternatively, you can use the [ command:
if [ -e {filename} ]; then
echo "File exists"
else
echo "File does not exist"
fiIn both cases, replace {filename} with the name of the file you want to check.
You can also use the -f option to check if the file exists and is a regular file:
if [ -f {filename} ]; then
echo "File exists and is a regular file"
else
echo "File does not exist or is not a regular file"
fiSimilarly, you can use the -d option to check if the file exists and is a directory:
if [ -d {filename} ]; then
echo "File exists and is a directory"
else
echo "File does not exist or is not a directory"
fiThese are just a few examples of how you can check if a file exists in a shell script. You can find more options and examples in the test or [ command documentation.