Here is a well-structured and elegant Bash script that loops through a predefined list of filenames and checks if each file exists in the current directory. If a file is missing, it prints the filename.
Script: check_missing_files.sh
#!/bin/bash
# Define the list of files to check (you can modify this list as needed)
files=("file1.txt" "file2.log" "document.pdf" "script.sh")
# Loop through each file in the list
for file in "${files[@]}"; do
# Check if the file does NOT exist in the current directory
if [[ ! -f "$file" ]]; then
echo "Missing file: $file"
fi
done
Explanation:
-
File List Definition:
- The
files array contains the names of the files you want to check. You can modify this list to include any filenames relevant to your use case.
-
Looping Through Files:
- The
for loop iterates over each element in the files array using "${files[@]}".
-
File Existence Check:
- The
-f flag checks if the file exists and is a regular file.
- The
[[ ! -f "$file" ]] condition evaluates to true if the file does not exist.
-
Output Missing Files:
- If the file is missing, the script prints the message
"Missing file: <filename>" to the terminal.
Usage Instructions:
- Save the script to a file, e.g.,
check_missing_files.sh.
- Make the script executable by running:
chmod +x check_missing_files.sh
- Run the script in the desired directory:
./check_missing_files.sh
Example Output:
Suppose the current directory contains only file1.txt and script.sh, but file2.log and document.pdf are missing. Running the script would produce:
Missing file: file2.log
Missing file: document.pdf
This script is simple yet powerful for verifying the presence of specific files in a directory. Let me know if you need further customization or enhancements!