122

I have a variable which has a string stored in it and need to check if it has lines in it:

var=`ls "$sdir" | grep "$input"`

pseudo-code:

while [ ! $var's number of lines -eq 1 ]
  do something

That's my idea on how to check it. echo $var | wc -l doesn't work - it always says 1, even though it has 3.

echo -e doesn't work as well.

9 Answers 9

144

Quotes matter.

echo "$var" | wc -l
10
  • 3
    That's not quotes surrounding the command, that's quotes surrounding the command substitution. The pairs of quotes will not interfere. Jun 11, 2011 at 19:02
  • 63
    This has a subtlety. An empty string will return 1 since echo on an empty string prints a newline. Aug 1, 2012 at 21:10
  • 3
    In other words: if [ -z "$var" ]; then printf '%s\n' '0'; else printf '%s\n' "${var%$'\n'}" | wc -l; fi. Try with var= (no lines), var='foo' and var=$'foo\n' (both one line in the *nix sense).
    – l0b0
    Jun 12, 2013 at 9:45
  • 2
    And yet another way to get it into a variable: LINE_COUNT=$(wc -l <<< "${var}") Jun 11, 2015 at 22:53
  • 7
    @Tim echo -n will simply decrease the count by one. @lucifurious echo $(wc -l <<< "${NONEXISTENTVAR}") still gives 1, not 0
    – Julian
    Feb 22, 2017 at 16:58
126

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
8
  • 1
    You're right. I swore I tested it, but I must have missed the double quotes or mistyped something. One or more whitespace chars does indeed get counted as 1 line as should be expected. I deleted my earlier comment to avoid confusing people. Mar 18, 2017 at 5:16
  • 7
    Perfect! This should be the accepted answer. It is the only solution so far that properly answers the question for all cases. Thanks for showing the test cases to prove it. Mar 18, 2017 at 5:17
  • 5
    YES! I too think this should be the accepted answer. Apr 18, 2017 at 14:32
  • 1
    This is correct, but can be simplified using printf rather than echo -n. I've added this as an alternate answer, in order to include test results. See below.
    – Stilez
    Feb 18, 2019 at 12:00
  • 1
    It says Suggested edit queue is full. Please, review the queue of the answer. We want to append, too!
    – Artfaith
    Mar 3, 2021 at 3:30
34

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).

11
  • 1
    I had to do this to get the correct answer: wc -l <<<"$(echo "$var")" (yes, every single symbol was necessary)
    – Nicolai S
    Jul 8, 2015 at 2:58
  • @NicolaiS Then you did something wrong. What was the content of $var?
    – speakr
    Jul 8, 2015 at 17:14
  • 1
    @NicolaiS That is correct because your var contains one line: You didn't interpret the \n with anything. Put multiple lines into your var and it will work, e.g. with var="foo<ENTER>bar<ENTER>baz"<ENTER>.
    – speakr
    Jul 9, 2015 at 8:10
  • 2
    xxd <<< '' create this hexdump 00000000: 0a. Therefore, <<< (Here Strings) add newline character to any contents.
    – MiniMax
    Jun 12, 2017 at 10:22
  • 1
    @MiniMax Thanks, I added your input to my answer. You can find an explanation for this behaviour here.
    – speakr
    Jun 12, 2017 at 11:05
14

No one has mentioned parameter expansion, so here are a couple of ways using pure bash.

Method 1

Remove non-newline characters, then get string length + 1. Quotes are important.

 var="${var//[!$'\n']/}"
 echo $((${#var} + 1))

Method 2

Convert to array, then get array length. For this to work, don't use quotes.

 set -f # disable glob (wildcard) expansion
 IFS=$'\n' # let's make sure we split on newline chars
 var=(${var})
 echo ${#var[@]}
4
  • 2
    Method 2 is cleaner and probably faster. Howver it relies on the IFS. So set IFS=$'\n' to make sure the variable is split at new lines when expanding it into an array: IFS=$'\n'; var=(${var})
    – untore
    Mar 12, 2019 at 5:16
  • I like Method 2 because of its minimum overhead: no external commands and not even a builtin is in sight. It's also quite readable. May 10, 2020 at 3:59
  • 1
    ShellCheck complains though: github.com/koalaman/shellcheck/wiki/SC2206. It's onto something. set -f is needed to avoid unwanted glob expansion. Try to use Method 2 on var=$'*\n.*'. May 10, 2020 at 4:15
  • 1
    auto-bonus for pure internal bash w/o external wc -l
    – nhed
    Jan 6, 2021 at 18:40
13

A simpler version of @Julian's answer, that works for all strings, with or without trailing \n (it does count a file containing just a single trailing \n as empty):

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

  • Returns zero: unset variable, empty string, string containing bare newline
  • Returns 1: any non-empty line, with or without trailing newline
  • etc

Output:

# a=
# printf "%s" "$a" | grep -c "^"
0

# a=""
# printf "%s" "$a" | grep -c "^"
0

# a="$(printf "")"
# printf "%s" "$a" | grep -c "^"
0

# a="$(printf "\n")"
# printf "%s" "$a" | grep -c "^"
0

# a="$(printf " \n")"
# printf "%s" "$a" | grep -c "^"
1

# a="$(printf " ")"
# printf "%s" "$a" | grep -c "^"
1

# a="aaa"
# printf "%s" "$a" | grep -c "^"
1

# a="$(printf "%s" "aaa")"
# printf "%s" "$a" | grep -c "^"
1

# a="$(printf "%s\n" "aaa")"
# printf "%s" "$a" | grep -c "^"
1

# a="$(printf "%s\n%s" "aaa" "bbb")"
# printf "%s" "$a" | grep -c "^"
2

# a="$(printf "%s\n%s\n" "aaa" "bbb")"
# printf "%s" "$a" | grep -c "^"
2
3
  • 1
    +1. Passing flags to echo (such as echo -n) is not standard, and may give different results on different implementations. Whereas printf does what we want by default. As a bonus, using printf saves you a process, since it's a shell built-in. (Suggestion: printf "$a" | wc -l is more concise and avoids unnecessary use of grep)
    – joshtch
    May 1, 2019 at 15:38
  • @joshtch Well.. no. As said by others in this discussion printf .... | wc -l will only remove one extra line (the newline) so that in case of an empty line the result will be 0. Correct. But if we pass 2 lines, the result will be 1, where the same variable passed to the printf ... | grep "^" will correctly return 2. Besides, using directly printf "$a" is very dangerous, because it can lead to silent errors if the string accidentally contains characters like %s, %d and so on... Same if the string starts with a dash. Instead, the 2 parameter in printf is automatically escaped Oct 9, 2020 at 1:32
  • This is not quite correct. The line a="$(printf "\n")" sets a to an empty string, not to a bare newline. To run the newline test in bash, try a=$'\n'; printf "%s" "$a" | grep -c "^". The count will be 1. If you want to omit ALL blank lines from the count, change the grep test from "^" to ".". Finally, as for printf vs. echo -n, it is technically true that printf is more portable. But in most situations echo -n is going to be just fine. Either command results in the same count for every test case. Jun 29, 2022 at 19:08
9

You can substitute the "wc -l" with "wc -w" to rather count the number of words instead of lines. This will not count any new lines and can be used to test if your original results are empty before you continue.

1
  • 1
    wc -l solutions outputs 1 even if the input variable is empty, so wc -w will be better to use.
    – Kadir
    Oct 13, 2015 at 8:41
5

Another method to count number of lines in a variable - assuming you did check it was successfully filled or it is not empty, for that just check $? after var subshell result affectation - :

readarray -t tab <<<"${var}"
echo ${#tab[@]}

readarray|mapfile is bash internal command which converts input file, or here string in this case, to array based on newlines.

-t flag prevents storing newlines at end of array's cells, useful for later use of stored values

Advantages of this method are :

  • no external command (wc, grep, ...)
  • no subshell (pipe)
  • no IFS issues (restore after modification, tricky to use with command-limited scope on internal commands, ...)
1
  • Which is typically more expensive, an extra process of a temporary file (due to here string)? Mar 21 at 19:08
4

To avoid filename in wc -l command:

lines=$(< "$filename" wc -l)
echo "$lines"
3

The top voted answers fail if no results were returned by a grep.

Homer Simpson
Marge Simpson
Bart Simpson
Lisa Simpson
Ned Flanders
Rod Flanders
Todd Flanders
Moe Szyslak

This is the wrong way to do it:

wiggums=$(grep -iF "Wiggum" characters.txt);
num_wiggums=$(echo "$wiggums" | wc -l);
echo "There are ${num_wiggums} here!";

There will tell us, there is 1 Wiggum in the list, even if there aren't any.

Instead, you need to do one extra check to see if the variable is empty (-z, as in "is zero"). If grep didn't return anything, the variable will be empty.

matches=$(grep -iF "VanHouten" characters.txt);

if [ -z "$matches" ]; then
    num_matches=0;
else
    num_matches=$(echo "$matches" | wc -l);
fi

echo "There are ${num_matches} VanHoutens on the list";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.