Shell – append text with echo without new line

echoio-redirectionshelltext processing

I want to append text to file like echo "abc" >>file.txt.

But this add abc after new line

How can I add abc in the end of file with echo without new line?

Best Answer

Assuming that the file does not already end in a newline and you simply want to append some more text without adding one, you can use the -n argument, e.g.

echo -n "some text here" >> file.txt

However, some UNIX systems do not provide this option; if that is the case you can use printf, e.g.

printf %s "some text here" >> file.txt

(the initial %s argument being to guard against the additional text having % formatting characters in it)

From man echo (on macOS High Sierra):

-n

Do not print the trailing newline character. This may also be achieved by appending '\c' to the end of the string, as is done by iBCS2 compatible systems. Note that this option as well as the effect of '\c' are implementation-defined in IEEE Std 1003.1-2001 ("POSIX.1") as amended by Cor. 1-2002. Applications aiming for maximum portability are strongly encouraged to use printf(1) to suppress the newline character.

Related Question