In bash, how do I count the number of lines in a variable?

Another way using here strings in bash:

wc -l <<< "$var"

As mentioned in this comment, an empty $var will result in 1 line instead of 0 lines because here strings add a newline character in this case (explanation).


The accepted answer and other answers posted here do not work in case of an empty variable (undefined or empty string).

This works:

echo -n "$VARIABLE" | grep -c '^'

For example:

ZERO=
ONE="just one line"
TWO="first
> second"

echo -n "$ZERO" | grep -c '^'
0
echo -n "$ONE" | grep -c '^'
1
echo -n "$TWO" | grep -c '^'
2

Quotes matter.

echo "$var" | wc -l

Tags:

String

Bash