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, echo
appends a newline character (\n) to the output. When you pipe the output of echo 987654321
to tail -c3
, it processes the string 987654321\n
.
If you don't want the echo
command to append a newline character, you can use the -n
flag:
echo -n 987654321 | tail -c3 # outputs 321
Note: The -n
flag in the echo command is not part of the POSIX standard i.e. some implementations of echo
may not support the -n
flag. So as mentioned by @Biffen, using the printf
command is recommended, which is more portable and adheres to the POSIX standard. Something like:
printf "987654321" | tail -c3