Reputation: 6365
I have a small script for disk usage logging, like this:
#!/bin/bash
date=$(date +"%d.%m.%Y")
while read -r filesystem;
do
filesys=${filesystem}
df -P | tr -d "%" | awk '$6=="'"$filesys"'" {print"'"$date"'"",",$6","$5}' >> /root/disk.csv
done < "/root/disklist"
/root/disklist:
/
/dev/mapper/map1
/root/disk.csv:
18.05.2015, /,18
18.05.2015, /dev/mapper/map1,1
When I run this script, print to new line of disk.csv. I need to see actual data, so when I run this script I need to update to same line about same date(not insert).
Not like this:
Run - 18.05.2015 13:00
18.05.2015, /,18
18.05.2015, /dev/mapper/map1,1
Run - 18.05.2015 15:00
18.05.2015, /,18
18.05.2015, /dev/mapper/map1,1
18.05.2015, /,19
18.05.2015, /dev/mapper/map1,5
When run this script, I need to change old line(if date same). How can I do this?
Upvotes: 3
Views: 99
Reputation: 70792
Care: you run df -P
without argument, (will generate full stat of all your disks) as many time, you had lines in your /root/disklist
.
So there is my purpose (using recent bash):
disklist=(
/home
/usr
/var
)
[ -f "/root/disklist" ] && disklist=($(</root/disklist))
file="/root/disk.csv"
printf -v myDate "%(%d.%m.%Y)T" -1
sed -e "/^$myDate,/d" $file >$file.tmp
df -P "${disklist[@]}" |
sed -ne 's/^.* \([0-9]\+\)% \(.*\)$/'$myDate', \2, \1/p' >>$file.tmp
read osize < <(stat -c%s $file)
read nsize < <(stat -c%s $file.tmp)
((nsize+=${#disklist[@]}*2)) # So length of % field could become smaller
[ $nsize -ge $osize ] && mv $file.tmp $file || rm -v $file.tmp >&2
The sed -e "/^$myDate,/d" -i $file
will inline edit $file
to drop all lines which begin by 18.05.2015,
, before appending reformated output of df -P
.
Upvotes: 4
Reputation: 203512
It's not completely clear what you want but maybe this will help:
#!/bin/bash
df -P | awk -v date="$(date +"%d.%m.%Y")" -v OFS=',' '
NR==FNR{disk[$1 OFS $2]=$3; next}
{disk[date OFS $6]=$5+0}
END {for (key in disk) print key, disk[key]}
' FS=',' /root/disk.csv FS=' ' - > tmp && mv tmp /root/disk.csv
Upvotes: 3