Created
June 29, 2024 16:58
-
-
Save basperheim/3c2ea62b2ed8fa14b236a4d31a805e7a to your computer and use it in GitHub Desktop.
Bash function that compares two files with color-coded printing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example use: