bash diff alternative

July 6, 2011

How to setup a bash diff alternative

nano -w /usr/bin/diff2

Copy and paste the below in to /usr/bin/diff2

#!/bin/bash
#
# name: diff2.sh
# usage: ./diff2.sh file1 file2
# To make available to whole system copy to /usr/local/bin
# and rename to diff2
# colorize diff output for ANSI terminals
# based on "diff2html"
# (http://www.linuxjournal.com/content/convert-diff-output-colorized-html)

# absolute color definitions
NOCOL="\e[0m"
BOLD="\e[1m"
RED="\e[31m"
BLUE="\e[34m"
PINK="\e[35m"
CYAN="\e[36m"
WHITE="\e[37m"

# style color definitions
C_COMMENT=$WHITE
C_DIFF=$RED
C_OLDFILE=$CYAN
C_NEWFILE=$RED
C_STATS=$BLUE
C_OLD=$BOLD$RED
C_NEW=$BOLD$BLUE
C_ONLY=$PINK

# check args
[[ $# -lt 2 ]] && echo "Usage: $0  file1 file2" && exit 1

# The -r option keeps the backslash from being an escape char.
diff -u $@ | while read -r s ; do
	# determine line color
	if [[ "${s:0:7}" == 'Only in' ]]; then color=$C_ONLY
	elif  [[ "${s:0:4}" == 'diff' ]]; then color=$C_DIFF
	elif  [[ "${s:0:3}" == '---'  ]]; then color=$C_OLDFILE
	elif  [[ "${s:0:3}" == '+++'  ]]; then color=$C_NEWFILE
	elif  [[ "${s:0:2}" == '@@'   ]]; then color=$C_STATS
	elif  [[ "${s:0:1}" == '+'    ]]; then color=$C_NEW
	elif  [[ "${s:0:1}" == '-'    ]]; then color=$C_OLD
	else color=
	fi

	# Output the line.
	if [[ "$color" ]]; then
		printf "$color"
		echo -n $s
		printf "$NOCOL\n"
	else echo $s
	fi
done

Now make it executable

chmod +x /usr/bin/diff2

Example Usage:

# bash -c 'diff2 < (sort file2) <(sort file1)'