echo in bash

Why does echo supress line breaks in bash?
I'm working on a script that starts like this:

words=`sort list.txt | uniq`
echo $words | wc -l

I need to number the lines and then do other stuff. I'd use jot, but it's not installed, so I hope I can get seq to do what I want. But first I need to figure out how many words there are. Of course, since the file is small, I could run "sort | uniq" twice, but it's a matter of principle... I'd rather save the output to a variable and then re-use it. But when I use "echo" and pipe it to wc -l, the output is 1, because the line breaks have been removed. Can anyone explain this behavior? I've tried echo -e, but it didn't make a difference.

It doesn't. The behavior you're getting is from bash itself. Unquoted string expansions get whitespace stripped and flattened.

words="`sort list.txt | uniq`"
echo "$words" | wc -l

Depending on how big the uniq output ends up being you might be better using a temporary file. Anything bigger than 4K isn't guaranteed to fit in an argument list on some shells.

1 Like

Off topic but instead of:

words=`sort list.txt | uniq`

I would suggest:

words=$(sort -u list.txt)