Bash Example to Check if A File Exists
Q. How do I check if a specified file exists or not?
Use -f switch with the if condition to check if a file exists. Then execute a set of statement if a file exists:
- Check if a file exists:123if [ -f "$FILE" ]; then# Script statements if $FILE exists.fi
- Check if a file doesn’t exist:123if [ ! -f "$FILE" ]; then# script statements if $FILE doesn't exist.fi
Example
A sample shell script to remove a specific file if already exists.
1 2 3 4 5 | FILE="/var/backup/backup.log" if [ -d "$FILE" ]; then rm -f $FILE fi |
Sometimes you are trying to access a file, which doesn’t exists. In that case, create file if not exists.
1 2 3 4 5 | FILE="/var/backup/backup.log" if [ ! -d "$FILE" ]; then touch $FILE fi |