back Tech:
DATE 20240729
If you need to compare files between two directories and generate a patch file, the following script can help you achieve this efficiently. This guide will explain the script's functionality and how to use it.
Here’s the shell script designed to compare files between two directories and create a patch file (filename.diff):
#!/bin/dash
# test if it is running as root and exit
if [ $(($(id -u))) -eq 0 ]; then
exit 0
fi
# check if it is in terminal
case "$(ps -o stat= -p $$)" in
*+*) echo "continue..." ;;
*) notify-send -t 2700 "clean exit" "please run it in terminal."; exit 0 ;;
esac
# test if it is already running and exit
SCRIPTNAME="$(basename "$(readlink -f "$0")")"
if pidof -x "$SCRIPTNAME" -o $$ >/dev/null 2>&1; then
echo "the script is already running."; exit 0
fi
cd "$PWD"
if ls . | grep "$3" >/dev/null 2>&1; then
echo "Oop! output file already exists. check first."; exit 0
fi
if ls "$1" | grep [[:space:]] >/dev/null 2>&1; then
echo "filename includes space in the folder "$1". correct it first."; exit 0
else
AFILES=$(ls "$1" | sort)
fi
if ls "$1" | grep [[:space:]] >/dev/null 2>&1; then
echo "filename includes space in the folder "$1". correct it first."; exit 0
else
BFILES=$(ls "$2" | sort)
fi
for i in $AFILES; do
if echo "$BFILES" | grep -w "$i" >/dev/null 2>&1; then
diff -u "$1"/"$i" "$2"/"$i" >> "$3".diff
else
# diff -u "$1"/"$i" /dev/null >> "$3".diff
echo "WARNING: "$1"/"$i" is not in "$2" folder"
fi
done
for ii in $BFILES; do
if ! echo "$AFILES" | grep -w "$ii" >/dev/null 2>&1; then
diff -u /dev/null "$2"/"$ii" >> "$3".diff
fi
done
generate_patch.sh
.chmod +x generate_patch.sh
to make the script executable.[user@hostname ~]$ ./generate_patch.sh dir1 dir2 output_filename
Assume you have two directories, old_version
and new_version
, containing the files you want to compare. To generate a patch file named update.diff
, run:
[user@hostname ~]$ ./generate_patch.sh old_version new_version update
In conclusion, this script is a useful tool for generating patch files by comparing files in two directories. By following the steps above, you can easily create patch files to track changes between different versions of your files.