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

  1. Open your terminal and start Vim by typing vim folder_diff.sh. This will create a new file named folder_diff.sh in your current folder and then open it in Vim.

  2. Press i to enter Insert mode, which allows you to edit the file. Now, copy and paste the following script into the editor:


# Check if the user has provided two arguments
if [ "$#" -ne 2 ]; then
    echo "Usage: ./folder_diff.sh <folder1> <folder2>"
    exit 1

# Check if the provided arguments are directories
if [ ! -d "$1" ] || [ ! -d "$2" ]; then
    echo "Error: Both arguments must be valid directory paths."
    exit 1

# Compare the directories recursively and display the differences
diff -rq "$1" "$2"
  1. Save and exit Vim by pressing Esc to switch to Command mode, then type :wq followed by Enter. This writes the changes to the file and exits the editor.

  2. 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?