File comparison is a common task in scripting and programming, especially when you want to verify the integrity of data or check for changes between two versions of a file. In this article, we will guide you through writing a shell script to compare two files, ‘file1.txt’ and ‘file2.txt,’ and determine whether they are identical or not.
Before we dive into creating the shell script for file comparison, you’ll need the following:
- A Unix-like operating system (Linux, macOS, or a compatible environment on Windows).
- A text editor (e.g., Vim, Nano, or VSCode) for creating and editing shell scripts.
- Basic knowledge of shell scripting.
Use your preferred text editor to create a new file. You can name it something like ‘compare_files.sh.’ To create it using the nano
text editor, run:
nano compare_files.sh
Write the Script
Inside ‘compare_files.sh,’ write the following shell script:
#!/bin/bash
# Define the files to be compared
file1="file1.txt"
file2="file2.txt"
# Compare the two files
if cmp -s "$file1" "$file2"; then
echo "The files $file1 and $file2 are identical."
else
echo "The files $file1 and $file2 are different."
fi
This script compares ‘file1.txt’ and ‘file2.txt’ using the cmp
command. If the files are identical, it will display a message indicating that. If they are different, it will indicate that as well.
Save the file and exit the text editor (e.g., in nano
, press Ctrl + O
to save and Ctrl + X
to exit).
Before running the script, make it executable using the following command:
chmod +x compare_files.sh
Now that the script is executable, you can run it to compare ‘file1.txt’ and ‘file2.txt’:
./compare_files.sh
The script will display whether the files are identical or different based on their content.
Read more on Shell and Linux related articles
Other urls to refer