Automated File Management in Bash: Check, Create, Append, and List Files Effortlessly
Introduction
This script is designed to perform three main functions:
Check if a specific file exists in the current directory.
Create the file if it does not exist.
Append a line of content to the file, then list all files in the directory.
This can be useful for automating file management tasks and ensuring specific files are updated regularly.
Code Explanation
#!/bin/bash
# Specify the file name
filename="myfile.txt"
# Check if the file exists
if [[ -f "$filename" ]]; then
echo "File '$filename' already exists."
else
echo "File '$filename' does not exist. Creating the file..."
touch "$filename"
echo "File '$filename' created."
fi
# Append content to the file
echo "Appending content to '$filename'."
echo "This is some new content added on $(date)" >> "$filename"
echo "Content appended successfully."
# List all files in the current directory
echo "Listing all files in the current directory:"
ls -l
Specify Filename: Sets a filename (
myfile.txt
) to be checked, created if missing, and updated with new content.File Check:
[[ -f "$filename" ]]
checks if the file exists.If it does, the script confirms it exists.
If it doesn’t,
touch "$filename"
creates the file.
Append Content:
echo "This is some new content added on $(date)" >> "$filename"
appends a new line with a timestamp to the file.List Files:
ls -l
displays all files in the current directory, along with file details like permissions and sizes.
Usage
Save the script as
file_
manager.sh
.Make the script executable:
chmod +x file_manager.sh
Run the script:
./file_manager.sh
Expected Output
The script will check the presence of myfile.txt
, create and append to it if needed, and then display the contents of the current directory. Here’s an example output:
File 'myfile.txt' does not exist. Creating the file...
File 'myfile.txt' created.
Appending content to 'myfile.txt'.
Content appended successfully.
Listing all files in the current directory:
total 4
-rw-r--r-- 1 user user 45 Oct 29 14:03 myfile.txt
-rwxr-xr-x 1 user user 368 Oct 29 14:02 file_manager.sh
Conclusion
This script provides a convenient way to manage file existence, creation, and content updates in Bash. It automates common file management tasks and can be easily customized to handle different filenames or append different content.