File Check and Replacement Script


This script verifies whether a file called e.txt exists and then renames it and creates a new empty file with the same name. It first sets a variable file_name and gives it the name e.txt. It then verifies whether the file exists or not using the -e flag. If the file exists, it displays "file exists" and renames the file by adding old to its name using the mv command. After renaming, it prints "New file filename_old" and then creates a new empty file with the original name by using the touch command. It prints "New empty file created with the name 'e.txt'". If the file does not exist, it just prints "Does not exist".
The script begins with #! /bin/bash, instructing the system to execute the script using the Bash shell. Next, it creates a variable file_name and assigns it the value e.txt, so the script will be executed with this file. The if statement verifies whether the file exists or not with -e, which is a test for checking the existence of the file. If the file exists, it outputs "file exists" to show that the file exists. It then renames the file by relocating it to a new name with old suffixed using the mv command. After renaming, it outputs "New file filename_old" to ensure the rename operation is successful. Then, it makes a new empty file with the original name using the touch command. It then outputs "New empty file created with the name 'e.txt'" to verify the creation of the new file.If the file does not exist, the script bypasses all these actions and just outputs "Does not exist".
#!/bin/bash
file_name="e.txt"
if [ -e "$file_name" ];
then
echo "file exists"
mv "$file_name" "${file_name}_old"
echo "New file file_name_old"
touch "$file_name"
echo "New empty file created with the name '$file_name'"
else
echo "Does not exist"
fi
Hope you learnt something new today
Happy Coding…
Subscribe to my newsletter
Read articles from Gagan G Saralaya directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
