#!/bin/bash # --- # A script to delete files in a target directory if they also exist in a reference directory. # --- # Exit immediately if a command exits with a non-zero status. set -e # Check if the correct number of arguments (two folders) was provided. if [ "$#" -ne 2 ]; then echo "Error: You must provide two directory paths." echo "Usage: $0 " echo " - target_directory: The folder FROM WHICH to delete files." echo " - reference_directory: The folder used as a reference FOR deletion." exit 1 fi TARGET_DIR="$1" REFERENCE_DIR="$2" # Check that both arguments are actual directories. if [ ! -d "$TARGET_DIR" ]; then echo "Error: Target directory '$TARGET_DIR' does not exist." exit 1 fi if [ ! -d "$REFERENCE_DIR" ]; then echo "Error: Reference directory '$REFERENCE_DIR' does not exist." exit 1 fi echo "Scanning for files in '$TARGET_DIR' to delete based on the contents of '$REFERENCE_DIR'..." echo "------------------------------------------------------------------" # Loop through every file in the reference directory. # This method correctly handles filenames that may contain spaces or special characters. find "$REFERENCE_DIR" -type f -print0 | while IFS= read -r -d '' reference_file; do # Get just the filename from the path. filename=$(basename "$reference_file") # Create the full path for the corresponding file in the target directory. target_file_path="$TARGET_DIR/$filename" # Check if that file actually exists in the target directory. if [ -f "$target_file_path" ]; then echo "Found match. Deleting: $target_file_path" # The actual delete command. rm "$target_file_path" fi done echo "------------------------------------------------------------------" echo "Script finished."