How to Empty a File in a bash Shell Script

The code is inside a loop that redirects output to a file. That file is then tested for whether it's empty or not. So, at the beginning of each iteration of the loop, I want to empty the file.

Can you tell me how to do that?

Something like this would be nice:

   FILE="$path/fileName"
   for ... do
      $FILE < EOF
      Other stuff...
      command 2> $FILE
      if $FILE not empty
          do something
      fi
   done
Jerry LAsked:
Who is Participating?
 
wilcoxonCommented:
To empty a file, you can just do:

cp /dev/null $FILE
0
 
sandipshahCommented:
Or delete the file and re-open it with the same name.

Ss
0
 
tel2Commented:
Or simply:

    >$FILE
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
ozoCommented:
command 2> $FILE
will empty the file before it writes
0
 
Jerry LAuthor Commented:
Thanks for all the suggestions.

1) cp /dev/null $FILE   >> is probably closest to what I was looking for.
2) Brute force is to delete and let first redirect "2>" create it when needed, again.
3) If ">$FILE" works, that may be most elegant.
4) command 2> $FILE doesn't help when testing loop iterations.
0
 
ozoCommented:
command 2> $FILE doesn't help when testing loop iterations.
what are you testing that it doesn't help?
0
 
Jerry LAuthor Commented:
>$FILE does work
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.