Chris Fritz
Chris Fritz

Reputation: 291

Output for loop to a file

I am trying to have a for loop output a text to a file 10 times. Here is what I have:

for ((i=1;i<=10;i++)); do
    echo "Hello World" >testforloop.txt
done

This outputs Hello World once to the file testforloop.txt. If I don't output to file it prints Hello World to the screen 10 times.

Upvotes: 11

Views: 35712

Answers (4)

basquiatraphaeu
basquiatraphaeu

Reputation: 667

The following will solve your problem:

You should try the >> operator for the reasons already mentioned with the command echo -e

Using option ‘\n‘ – New line with backspace interpretor ‘-e‘ treats new line from where it is used.

link

Doing so:

for ((i=1;i<=10;i++)) ; do echo -e "Hello World" >> testforloop.txt ; done

cat command:

cat testforloop.txt

output:

Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World

Alternatively, you can try:

cat -n testforloop.txt

output:

1 Hello World 2 Hello World 3 Hello World 4 Hello World 5 Hello World 6 Hello World 7 Hello World 8 Hello World 9 Hello World 10 Hello World

Upvotes: 0

Lando Calrissian
Lando Calrissian

Reputation: 17

You rewrite the testforloop.txt ten times. If you did

for ((i=1;i<=10;i++)) ; do echo "Hello World" > testforloop(i).txt ; done

where i is the int from the for loop. I'm not sure the language you're programming in.

Upvotes: -1

torek
torek

Reputation: 489858

You are using > redirection, which wipes out the existing contents of the file and replaces it with the command's output, inside the loop. So this wipes out the previous contents 10 times, replacing it with one line each time.

Without the >, or with >/dev/tty, it goes to your display, where > cannot wipe anything out so you see all ten copies.

You could use >>, which will still open the file ten times, but will append (not wipe out previous contents) each time. That's not terribly efficient though, and it retains data from a previous run (which may or may not be what you want).

Or, you can redirect the entire loop once:

for ... do cmd; done >file

which runs the entire loop with output redirected, creating (or, with >>, opening for append) only once.

Upvotes: 16

rakib_
rakib_

Reputation: 142885

You're only redirecting the echo with ">", so it overwrites. What you need is to append using ">>" operator. Do the following:

       for ((i=1;i<=10;i++)) ; do echo "Hello World" >> testforloop.txt ;  done

Upvotes: 6

Related Questions