2 minutes
Comparing Folders Recursively with a Simple Bash Script
I often need to compare the contents of two directories to identify differences, whether for troubleshooting, synchronization, or verifying backups. I thought I should write down the script I put together to stop searching for it all the time.
So here’s how to create and use a simple bash script that recursively compares two folders and displays their differences in terms of files and folders. I also create and save all scripts using the Vim text editor.
Creating the Bash Script
Open your terminal and start Vim by typing
vim folder_diff.sh
. This will create a new file namedfolder_diff.sh
in your current folder and then open it in Vim.Press
i
to enter Insert mode, which allows you to edit the file. Now, copy and paste the following script into the editor:
#!/bin/bash
# Check if the user has provided two arguments
if [ "$#" -ne 2 ]; then
echo "Usage: ./folder_diff.sh <folder1> <folder2>"
exit 1
fi
# Check if the provided arguments are directories
if [ ! -d "$1" ] || [ ! -d "$2" ]; then
echo "Error: Both arguments must be valid directory paths."
exit 1
fi
# Compare the directories recursively and display the differences
diff -rq "$1" "$2"
Save and exit Vim by pressing
Esc
to switch to Command mode, then type:wq
followed byEnter
. This writes the changes to the file and exits the editor.Make the script executable by running the following command in your terminal:
chmod +x folder_diff.sh
.
Using the Bash Script
To use the script, simply provide two folder paths as arguments:
./folder_diff.sh /path/to/folder1 /path/to/folder2
The script will output the differences between the two folders, including any files or folders unique to each directory.
Yeah it’simple. But that’s the point right?