DEV Community

BC
BC

Posted on

echo content to file

You can use the echo command to put some content into a file, but by default it will add a trailing "newline character" to the file. So if you are calculate file's fingerprint, you need to know it calculated the newline character.

For example, if you echo "hello" to a file then calculate the md5, the value will be different from direct calculate md5("hello").

If you don't want echo to add this newline character, you could use the -n option:

$ man echo
-n,  Do not print the trailing newline character
Enter fullscreen mode Exit fullscreen mode

Example:

$ echo "hello" > a1.txt
$ md5 a1.txt
MD5 (a1.txt) = b1946ac92492d2347c6235b4d2611184
$ cat a1.txt
hello
$ echo -n "hello" > a2.txt
$ md5 a2.txt
MD5 (a2.txt) = 5d41402abc4b2a76b9719d911017c592
$ cat a2.txt
hello%
Enter fullscreen mode Exit fullscreen mode

You can see when use echo -n then use cat to show the file content, it will display an extra "%" to indicate that there is no "newline character". Also you can see, with and without the -n option, the md5 value are different.

Top comments (1)

Collapse
 
moopet profile image
Ben Sinclair • Edited

I'd recommend using printf instead of echo, since echo is much more loosely-defined; different implementations use different flags and behaviours and while you're unlikely to run into problems, you might. If, as in your example, you're relying on an exact hash match for something, then printf is the way to go, as it's completely locked-down in terms of behaviour by POSIX.