If I run
git diff --color=always | less
Here's a bash script to do the job:
#!/bin/bash num_lines=$(git diff | wc -l) if [ $num_lines -eq 0 ] then echo "No changes" else git diff --color=always | less --raw-control-chars fi
git diff --color=always | (IFS=$'\n' read -r A; if [ -n "$A" ]; then (printf '%s\n' "$A"; cat) | less --raw-control-chars; else echo "No changes"; fi)
The one-liner has the advantage of only running
git diff once for better performance.
Some explanation per @tripleee's comment:
You should properly use
read -rto not unintentionally mangle the first line. This will still mangle leading or trailing whitespace. You can fix that with
echomight throw an error or behave strangely if the first line starts with a dash (which looks to
echolike an option argument) -- use
printf '%s\n' "$A"instead to avoid that.
In both cases, the
--raw-control-chars option (short version
-r) passed to
less will cause the colors to show up correctly.