Bash How to Check If File Exists
What is the definition file in Linux? The file is almost everything – keyboard, and disk, and the regular file. Here is an example of a 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 a 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 tune the 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 the test command.
Here are some examples of file test operators:
Option | Test |
-s | File is a regular file (if the 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 |