If a file exists then do (something) in bash

If you need to determine in a file exists in a directory use the first example.

Credit to http://stackoverflow.com/questions/638975/how-do-i-tell-if-a-file-does-not-exist-in-bash for a simple answer.


#!/bin/bash
if [ -f path/to/file.txt ]
then
echo "file exists"
fi

If you need to know if it does not exist use this:

#!/bin/bash
if [ ! -f path/to/file.txt ]
then
echo "file does not exist"
fi

I had a list of files in "your_files.txt" and needed to know if they were in a directory or not. Combining read lines in a text file with bash to loop thru the list of files I was looking for and the "if  [ -f file.txt ]" was a fast way to find out.

#!/bin/bash
while read line
do
if [ -f path/to/$line ]
then
echo "$line exists"
else
echo "$line does not exist"
fi
done < your_files.txt

Leave a Reply