How to count the line number of a file?

How to count the line number of a file? It seems an easy question for Unix guys: using wc command. Let’s see an example:

# cat test
aaaa
bbbb
cccc
# wc -l test
3 test

It displays right. But wait a minute, let’s check the wc -l option meaning:

# wc --help
......
-l, --lines            print the newline counts
......

wc -l just print the newline counts, so it increases newline count as the line number. Using hexdump to see the content of test:

# hexdump -C test
00000000  61 61 61 61 0a 62 62 62  62 0a 63 63 63 63 0a     |aaaa.bbbb.cccc.|
0000000f

No problem, test contains 3 newlines. But now, the question is here, how about the last line doesn’t contain newline?

Let me do the following experiment:

# echo -n "a" > test
# hexdump -C test
00000000  61                                                |a|
00000001
# wc -l test
0 test

Now the test file only contains 1 character, and no newline. This time, wc -l thinks there is no line in test file.

Based on the previous discussion, maybe awk is a better tool when using to count line number of file. Just one statement:

# awk 'END {print NR}' test
1

It outputs right line number.