• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 731
  • Last Modified:

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
0
WizeOwl
Asked:
WizeOwl
3 Solutions
 
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
Nothing ever in the clear!

This technical paper will help you implement VMware’s VM encryption as well as implement Veeam encryption which together will achieve the nothing ever in the clear goal. If a bad guy steals VMs, backups or traffic they get nothing.

 
ozoCommented:
command 2> $FILE
will empty the file before it writes
0
 
WizeOwlAuthor 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
 
WizeOwlAuthor Commented:
>$FILE does work
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now