1

If I'm in terminal and I write some basic string to a file, is there a way to continually append to that file using echo?

For instance, echo 'hello' > file will put 'hello' into that file, but what if I now want to append ' world' to file? I know that if I do echo ' world', it'll overwrite the first string I wrote into file. Is there any += operator I can use in bash?

EDIT: Nevermind, I can append using >>. Is it possible to append to the same line instead of to a new line?

Sidd26
  • 13
  • 1
  • 4

1 Answers1

8
echo -n 'Hello' > file
echo ', World!' >> file

The >> redirection operator means "append."

Here we're using a non-standard extension of echo, where -n tells it not to append a new line.

If you want standard-compliant behavior, use printf:

printf 'Hello' > file
printf ', World!\n' >> file

Edit: using double quote around a string containing the exclamation ! may not work with some versions. It could get interpreted as a history expansion token. Use single quotes to prevent this.

Cong Ma
  • 10,692
  • 3
  • 31
  • 47