1

I am writing a shell script in which I have a loop. As the loop goes through different values get assigned to the variable i . I want to echo all the values that get i gets assigned each time the loop runs, into a text file.

What I am doing is at the moment is:

echo " $i " > fail

but that only gets me the last value that was assigned to i .

4 Answers 4

2

Instead of redirecting the individual echo to your file, redirect the entire loop to the file. This is considerably more efficient, and truncates the file only once, when the loop is started.

for i in "${whatever[@]}"; do
   echo "  $i"
done >fail

If you don't want to truncate the file at all, of course, you can use >>fail in the same position.

Sign up to request clarification or add additional context in comments.

Comments

1

If you use

echo " $i" >> fail

It will append it to the file.

1 Comment

Works, to be sure -- but unnecessarily inefficient to re-open a file every time you want to write just one line to it.
1

Put

echo " $i " >> fail

within the loop.

1 Comment

> fail is what he is doing, which will override the file every time.
0

echo " $i" > fail Will write to the file (overwrite)

echo " $i" >> fail Will append to the existing file

1 Comment

Actually, putting the redirection after the loop often makes more sense. Putting ...command... >>file inside a loop re-opens the file every time the loop is executed, with the obvious performance/efficiency impact.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.