Search code examples
linuxbashshelldiff

Why does linux shell diff command sometimes show output related to empty lines even though -B (--ignore-blank-lines) option is present?


Linux diff command accepts an option that instructs it to "ignore changes where lines are all blank", as per the manual page.

And while trying this option, I came across a situation where blank lines seem to not be ignored, even though -B (or --ignore-blank-lines) option is used.

Here follows a working script that demonstrates the issue:

#!/bin/bash

echo -e 'a\nb\nc' > file_a1
echo -e 'a\n\nb'  > file_a2

echo
echo \ file_a1
cat    file_a1
# a
# b
# c

echo
echo \ file_a2
cat    file_a2
# a
#
# b

echo
echo \ regular diff
diff    file_a1 file_a2
# 1a2
# >        <- output related to empty line
# 3d3
# < c

echo
echo \ diff -B : empty lines ignored, as expected
diff -B file_a1 file_a2
# 3d3
# < c

echo -e 'a\nb' > file_b1
echo -e '\nb'  > file_b2

echo
echo \ file_b1
cat    file_b1
# a
# b

echo
echo \ file_b2
cat    file_b2
#
# b

echo
echo \ regular diff
diff    file_b1 file_b2
# 1c1
# < a
# ---
# >        <- output related to empty line

echo
echo \ diff -B : same output, as if -B option was not present
diff -B file_b1 file_b2
# 1c1
# < a
# ---
# >        <- output related to empty line

echo
echo \ diff version
diff --version
# diff (GNU diffutils) 3.9
# Copyright (C) 2023 Free Software Foundation, Inc.
# License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
# This is free software: you are free to change and redistribute it.
# There is NO WARRANTY, to the extent permitted by law.
# 
# Written by Paul Eggert, Mike Haertel, David Hayes,
# Richard Stallman, and Len Tower.

Solution

  • Like the man page tells you, -B applies where the only changes are in whitespace. In your file_b* example, something changed into an empty line, so "lines are all blank" is untrue.

    You could argue that the description is ambiguous, but this is what I believe it means.