How do I count the number of lines in a bash variable, respecting emptiness?

694 Views Asked by At

We know how to count the number of lines in a variable. However, as noted in comments and answers there, the semantics are quirky when it comes to empty variables, as an empty variable is usually counted the same as a non-empty, no-newline variable:

$ echo -n "" | wc -l
0
$ echo -n "foo" | wc -l
0
$ echo "" | wc -l
1
$ echo "foo" | wc -l
1

not so good, if you want to count the number of results some other command returned.

Now, a partial workaround is suggested in one of the answers to that question:

printf "%s" "$a" | grep -c "^"

but that's not exactly what I'm after either, since it counts a non-empty variable whose value is a newline as having 0 lines.

My question: Other than counting "regularly" and then explicitly checking for the case of emptiness, is there a decent way to obtain such a count in bash?

2

There are 2 best solutions below

1
On BEST ANSWER

awk to the rescue:

$ echo -n "foo" | awk 'END {print NR}'
1
$ echo -n "" | awk 'END {print NR}'
0
0
On

The following will count the number of newlines:

printf %s "$var" | tr -d -c '\n' | wc -c

It will work in all instances except when the last line is missing a newline.


You can test separately if a variable is empty like this:

test -z "$var" && echo "var is empty"

test -n "$var" && echo "var is not empty"