Using only bash, diff, tput, and less, we can closely approximate the output of git diff. There will be some notable differences, though, due to the short-sightedness of the diff programmers.
Put the following Bash function definition in some file that gets sourced automatically by your user account, and you'll be able to access the function from the command line:
function gdiff()
{
local REG=`tput op`
local GRP=`tput setaf 6`
local ADD=`tput setaf 2`
local REM=`tput setaf 1`
local NL=$'\n'
local GRP_LABEL="${GRP}@@ %df,%dn +%dF,%dN @@${REG}"
local UNCH_GRP_FMT=''
[[ "${1}" == '@full' ]] && {
UNCH_GRP_FMT="${GRP_LABEL}${NL}%="
shift
}
diff \
--new-line-format="${ADD}+%L${REG}" \
--old-line-format="${REM}-%L${REG}" \
--unchanged-line-format=" %L${REG}" \
--new-group-format="${GRP_LABEL}${NL}%>" \
--old-group-format="${GRP_LABEL}${NL}%<" \
--changed-group-format="${GRP_LABEL}${NL}%<%>" \
--unchanged-group-format="${UNCH_GRP_FMT}" \
"${@}" | less -FXR
}
This function works as follows:
- Ultimately,
diff gets invoked with various formatting options to specify how changes within the files will be displayed.
tput is used to insert ANSI color codes into those formatting options. Note that when using non-ANSI terminals, you may have to replace tput setaf with tput setf.
- The output of
diff is piped into less. -R allows ANSI colors to be preserved. -X prevents less from clearing the screen upon exiting. -F prevents less from operating as a pager if the output fits within one screen.
- If the first parameter is
@full, the function will display all unchanged lines in addition to added and removed lines.
Note the following differences between this approach and git diff:
git diff reports three lines of context surrounding each change. Unfortunately, diff seems to complain and exit if you want to specify the number of context lines while also simultaneously specifying formatting options. (At least it does in Mac OS X Yosemite). Thanks diff programmers. Therefore, you can either request no lines of context surrounding each change, which is the default behavior, or you can request that all unchanged lines within the file are also reported, by specifying @full as the first parameter.
- Because the lines of context are different from
git diff, the line numbers reported by this function will also vary from those reported by git diff.
- You may see the presence of single-line changes reported, which is the correct behavior, but annoying when your changed file contains the insertion of single empty lines. I think
git diff deals with this better, via its lines of context. You could try passing different options to diff to better deal with whitespace, if you prefer.
newtextin/etc/colordiff. I think git uses green?git diff --no-indexstill respect Git's "ignore" entries? If so, you could make a wrapper script that temporarily creates a.gitignorefile, or maybe there's a way to pass ignore entries on the command-line as inline config or something like that.