Skip to content

Instantly share code, notes, and snippets.

@basperheim
Created June 29, 2024 16:58
Show Gist options
  • Save basperheim/3c2ea62b2ed8fa14b236a4d31a805e7a to your computer and use it in GitHub Desktop.
Save basperheim/3c2ea62b2ed8fa14b236a4d31a805e7a to your computer and use it in GitHub Desktop.
Bash function that compares two files with color-coded printing
compare_files() {
if [ "$#" -ne 2 ]; then
echo "Usage: compare_files <file1> <file2>"
return 1
fi
local file1="$1"
local file2="$2"
if [ ! -f "$file1" ]; then
echo "Error: File '$file1' not found."
return 1
fi
if [ ! -f "$file2" ]; then
echo "Error: File '$file2' not found."
return 1
fi
diff_output=$(diff -u "$file1" "$file2")
diff_exit_code=$?
if [ $diff_exit_code -eq 0 ]; then
echo "Files '$file1' and '$file2' are identical."
else
echo "Differences between '$file1' and '$file2':"
while IFS= read -r line; do
case "$line" in
-*)
# Deletions (red)
echo -e "\x1b[31m$line\x1b[37m"
;;
+*)
# Additions (green)
echo -e "\x1b[32m$line\x1b[37m"
;;
*)
# Unchanged (default color)
echo -e "\x1b[37m$line\x1b[37m"
;;
esac
done <<< "$diff_output"
fi
}
@basperheim
Copy link
Author

Example use:

echo 'hello' >> test1.txt
echo 'hello\nworld' >> test2.txt
echo 'hello world' >> test3.txt

compare_files test1.txt test2.txt                                    
Differences between 'test1.txt' and 'test2.txt':
--- test1.txt	2024-06-29 11:51:12
+++ test2.txt	2024-06-29 11:51:19
@@ -1 +1,2 @@
 hello
+world

compare_files test1.txt test3.txt
Differences between 'test1.txt' and 'test3.txt':
--- test1.txt	2024-06-29 11:51:12
+++ test3.txt	2024-06-29 11:51:24
@@ -1 +1 @@
-hello
+hello world

compare_files test2.txt test3.txt
Differences between 'test2.txt' and 'test3.txt':
--- test2.txt	2024-06-29 11:51:19
+++ test3.txt	2024-06-29 11:51:24
@@ -1,2 +1 @@
-hello
-world
+hello world

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment