head -c 3 sample.txt
The output will display before username in the prompt.
Theuser@localhost:/home$
The
is not being printed after $
.
Why is my terminal doing this?
head -c 3 sample.txt
The output will display before username in the prompt.
Theuser@localhost:/home$
The
is not being printed after $
.
Why is my terminal doing this?
The
is not being printed after$
Why should it? head
prints first and only then the shell prompts you for the next command. It's somewhat reasonable to expect the prompt in a separate line though, still after (below) The
.
head -c 3 sample.txt
printed exactly The
and there was no newline character after e
. You requested head
to print 3 bytes to its stdout (i.e. to the terminal in this case) and you got exactly 3 bytes. There was no newline character among them.
Usually a textual output from a command (e.g. from echo
) ends with a newline character. When the shell prints the prompt after the command terminates, it prints immediately after the newline, so you see the prompt at the beginning of a new line.
In your case there was no newline after The
, therefore when the shell printed to the terminal, the prompt appeared in the same line.
Some shells detect when this is about to happen. Your shell apparently doesn't.
Tools that deal with lines print them with trailing newline characters because these characters actually belong to their respective lines. A situation where the last line in the source data (e.g. sample.txt
) is incomplete (i.e. there is no trailing newline) may be handled by ignoring the line or by printing as-is (without newline character) or by fixing (adding a newline character); this depends on the tool and its implementation.
From sample.txt
containing complete lines and from head -n
that deals with lines you can expect complete lines. But head -c
deals with bytes and unless you know in advance the last byte to be printed is a newline character, you shouldn't assume the last line of the output will be complete.
You can easily add a newline character by invoking echo
without arguments just after head
:
head -c 3 sample.txt; echo
Then your prompt will appear in a separate line almost* for sure. Just remember this one newline comes from echo
, not from sample.txt
.
* The exception is when the output from head
contains terminal control sequence(s) moving the cursor around etc. I don't expect such sequences to fit into three bytes but in general if the file contains them and if the terminal understands them and if you request enough bytes then the terminal will obey. If this happens, it's possible to see the prompt in any place (or worse)