bash how to check if file exists

Answer

What is the definition file in Linux? The file is almost everything - keyboard, and disk, and the regular file. Here is example of regular file: document.odt or /etc/passwd.

If you want the script to find out if there is any file (eg. tile.txt or /dev/sda), you can do the following:

if [ -e /root/file.txt ]; then
echo  "File found";
fi

So, we tested if any kind of file (named /root/file.txt) exists.

If you want to take into consideration just regular files (not /dev/sda but just /root/file.txt), you can use -f parameter instead of -e parameter:

if [ -f /root/file.txt ]; then
echo  "Regular file found";
fi

If you want to check, if regular file not exists, you can use not(!) in test command []:

if [ ! -f /root/file.txt ]; then
echo  "Regular file not found";
fi

We could to tune last example. You can also use short way how to write it:

[ ! -f /root/file.txt ] && echo  "Regular file not found"

It is my favorite, if you have just one command after test command.

Here are some examples of file test operators:

Option Test
-s File is a regular file (if file is directory or device returns false)
-d File is a directory
-b File is a block device
-c File is a character device
-p File is a pipe
-w File has a write permission

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.