I often use the technique described in the accepted answer:
diff <(ls old) <(ls new)
but I find I usually use it with much more complex commands than the example above. In such cases it can be annoying to craft the diff command. I have come up with some solutions that others may find useful.
I find that 99% of the time I try out the relevant commands before running diff. Consequently the commands I want to diff are right there in my history ... why not use them?
I make use of the Fix Command (fc) bash builtin to execute the last two commands:
$ echo A
A
$ echo B
B
$ diff --color <( $(fc -ln -1 -1) ) <( $(fc -ln -2 -2 ) )
1c1
< B
---
> A
The fc flags are:
-n: No number. It suppresses the command numbers when listing.
-l: Listing: The commands are listed on standard output.
the -1
-1
refer to the start and end position in the history, in this case its from the last command to the last command which yields just the last command.
Lastly we wrap this in $()
to execute the command in a subshell.
Obviously this is a bit of a pain to type so we can create an alias:
alias dl='diff --color <( $(fc -ln -1 -1) ) <( $(fc -ln -2 -2 ) )'
Or we can create a function:
dl() {
if [[ -z "$1" ]]; then
first="1"
else
first="$1"
fi
if [[ -z "$2" ]]; then
last="2"
else
last="$2"
fi
# shellcheck disable=SC2091
diff --color <( $(fc -ln "-$first" "-$first") ) <( $(fc -ln "-$last" "-$last") )
}
which supports specifying the history lines to use. After using both I find the alias is the version I prefer.