Comparing Two Files in Shell Script

Shell Scripting @

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:

  1. A Unix-like operating system (Linux, macOS, or a compatible environment on Windows).
  2. A text editor (e.g., Vim, Nano, or VSCode) for creating and editing shell scripts.
  3. Basic knowledge of shell scripting.

Use your preferred text editor to create a new file. You can name it something like ‘’ To create it using the nano text editor, run:


Write the Script

Inside ‘,’ write the following shell script:

# Define the files to be compared
# Compare the two files
if cmp -s "$file1" "$file2"; then
  echo "The files $file1 and $file2 are identical."
  echo "The files $file1 and $file2 are different."

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

Now that the script is executable, you can run it to compare ‘file1.txt’ and ‘file2.txt’:


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

  1. PySpark Blogs
Author: user