Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
982 views
in Technique[技术] by (71.8m points)

bash - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...