0
0
Bash Scriptingscripting~5 mins

File existence checks in Bash Scripting

Choose your learning style9 modes available
Introduction
Checking if a file exists helps your script decide what to do next, like reading a file or creating it if missing.
Before reading a file to avoid errors if the file is missing.
Before writing to a file to prevent overwriting important data.
To check if a configuration file is present before starting a program.
To verify if a backup file exists before restoring data.
To confirm if a log file is available before appending new logs.
Syntax
Bash Scripting
[ -e filename ]
Use -e to check if a file or directory exists.
Use [ ] with spaces around brackets and operators.
Examples
Checks if 'myfile.txt' exists.
Bash Scripting
[ -e myfile.txt ]
Checks if 'myfile.txt' exists and is a regular file.
Bash Scripting
[ -f myfile.txt ]
Checks if 'myfolder' exists and is a directory.
Bash Scripting
[ -d myfolder ]
Sample Program
This script checks if 'example.txt' exists in the current folder and prints a message accordingly.
Bash Scripting
#!/bin/bash

filename="example.txt"

if [ -e "$filename" ]; then
  echo "File '$filename' exists."
else
  echo "File '$filename' does not exist."
fi
OutputSuccess
Important Notes
Always put spaces around [ and ] and between operators.
Use quotes around filenames to handle spaces or special characters.
Use -f for regular files and -d for directories when you want specific checks.
Summary
Use [ -e filename ] to check if a file or directory exists.
Use if-else to run different commands based on file existence.
Quotes around filenames help avoid errors with spaces.