akirakio
akirakio

Reputation: 13

How to echo $variable into text file within a loop

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 .

Upvotes: 1

Views: 2470

Answers (4)

Drewness
Drewness

Reputation: 5072

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

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

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295278

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.

Upvotes: 2

Karsten S.
Karsten S.

Reputation: 2391

If you use

echo " $i" >> fail

It will append it to the file.

Upvotes: 1

Vivek Vermani
Vivek Vermani

Reputation: 2004

Put

echo " $i " >> fail

within the loop.

Upvotes: 1

Related Questions