Can I remove a newline if I redirect output like this?

echo "a" >> file

I have something similar in my script which contains a for loop that redirects every character (except numbers) to a file. But my goal is to have this output in one line. Let's say I redirect the "a" ten times so it should look like this:

a a a a a a a a a a

but it looks like this:

  • 1
    Use echo -n or printf. Commented Jan 2, 2019 at 19:35
  • I should have looked at man echo in the first place. Thanks a lot!
    – KKor
    Commented Jan 2, 2019 at 19:38
  • 3
    @KKor don't rely on man echo - your shell may have a builtin echo command that behaves differently. See for example Why is printf better than echo? Commented Jan 2, 2019 at 19:47

3 Answers 3


If you're specifically asking about echo, you can use -n to suppress the newline:

$ echo -n "test" >> outputfile

If you're asking more generally how to suppress newlines in piped or redirected data, this is a cat with many skins. One easy way is with tr:

$ do_stuff | tr -d "\n" >> outputfile

If you're just getting started with scripting and outputting data, it might be best to get out of the habit of using echo altogether in favor of printf:

$ printf "test" >> outputfile

printf is superior to echo in many ways and for many reasons, not least of which is that it only prints what you explicitly tell it to (and, arguably more importantly, in the format in which you want it).


I don't think you'd want to delete the newlines, but replace them with spaces:

for ((i=0; i<10; ++i)); do
    echo a
done | tr '\n' ' ' >file

This simply post-processes your echo output and saves the data into file (truncating it first, if it already exists).

Or do something more fancy (in bash),

for ((i=0; i<10; ++i)); do
    array+=( "a" )

printf '%s\n' "${array[*]}" >file

This has the advantage of terminating the line properly with a final newline, while all the elements of the array are delimited by space (the first character of $IFS).

Or, with /bin/sh:

set --
while [ "$i" -lt 10 ]; do
    set -- "$@" "a"
    i=$(( i + 1 ))

printf '%s\n' "$*" >file
for i in `seq 1 10`; do
  printf "a " >> file

should do the trick.

  • 1
    or for ... do ... done >> file to avoid reopening file multiple times
    – Jeff Schaller
    Commented Jan 2, 2019 at 20:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .