Preserve trailing whitespace in variable

Hello,

I wondering how I can echo a string without having the trailing whitespace removed.

For example I have a string str="TESTING123 " that I need to hash using sha1. I get the correct answer when I run the line below from the terminal

$ echo -n "TESTING123 " | openssl sha1
fe1a126175cf589be634fc3a41a7701a78f5ad28

However when I pass the string as a variable I get a different answer as the trailing whitespace is removed.

str="TESTING123 "
echo -n $str | openssl sha1
18aa7ac11356238ef89cfbd2875727dcd054d6ed

Is there a particular way I should declare this variable or something?

Regards,
Colin

echo -n "$str"

Simple as...

Thanks for your help balajesuri

It's advised to always double quote variable in a shell script.

"$var"

The reason for that is treating shell code and shell data in variables equivalently! Not like in other languages that line of code is different entity/type of text than line of string stored under variable. Here it is the same.

In your case $str is expanded correctly with space at the end, but it is then just space in a command line, so it is discarded

You can find more info in this article http://www.cofoh.com/white-shell