When I open my terminal and input the command echo 987654321 | tail -c3, the output is 21.
However, when I create a file named test_tail.sh, write 987654321 into the file, the command tail -c3 test_tail.sh prints 321.
Why these different results? According to the manual, tail -cNUM shows the last NUM bytes of a file. So, I'm curious why echo 987654321 | tail -c3 in the terminal prints 21.
By default,
echoappends a newline character (\n) to the output. When you pipe the output ofecho 987654321totail -c3, it processes the string987654321\n.If you don't want the
echocommand to append a newline character, you can use the-nflag:Note: The
-nflag in the echo command is not part of the POSIX standard i.e. some implementations ofechomay not support the-nflag. So as mentioned by @Biffen, using theprintfcommand is recommended, which is more portable and adheres to the POSIX standard. Something like: