anarchy
anarchy

Reputation: 5184

shell script delete file before creating file

I have the following script,

#!/bin/bash

for data in $(someprogram withsomeargument)
do                      
      IFS=',' read -r -a dataArray<<< "$data"
      NAME="${dataArray[0]}"
      DATE="${dataArray[3]}" 

      echo "$DATE" >> ~/Documents/testing/files/dates.txt
done       

it saves dates line by line into the dates.txt folder.

I want to add rm ~/Documents/testing/files/dates.txt at the front to make sure that there is no file before the script runs, but when I run it multiple times, the file doesn't get deleted, it just keeps appending the data from the previous run.

How do I make sure the dates.txt file is deleted before the script is run if the file exists?

Upvotes: 0

Views: 325

Answers (1)

Cyrus
Cyrus

Reputation: 88644

Remove >> ~/Documents/testing/files/dates.txt after echo and

append > ~/Documents/testing/files/dates.txt after done. No need for rm.

for data in $(someprogram withsomeargument)
do                      
      IFS=',' read -r -a dataArray<<< "$data"
      NAME="${dataArray[0]}"
      DATE="${dataArray[3]}" 

      echo "$DATE"
done > ~/Documents/testing/files/dates.txt

Upvotes: 3

Related Questions