I'm working on a bash code which would enter the command df-h, loop through the disk usage fields and print the number using awk and if any of the disk usage reaches over 85 percent, it would find the files older than 3 days within the log path indicated in variable and remove them.
However upon trying to run the script, it constantly complains that the command was not found on line 6.
This is the code that I'm working on
files =$(find /files/logs -type f -mtime 3 -name '*.log)
process =$(df-h | awk '{print $5 0}')
for i in process
do
if $i -ge 85
then
for k in $files
do
rm -rf $k
done
fi
done;
Its so irritating because I feel that I'm so close to the solution and yet I still cant figure out as to whats wrong with the script that it refuses to work
CodePudding user response:
you are searching files in /files/logs so you are probably only interested in this partition (root partition?)
- your if statement did not respect the proper syntax... should be
if [[ x -gt y ]]; then
.... - there was no need to loop thhrough the files collected by find since you can use
-exec
directly in find (seeman find
)
#!/bin/bash
# find the partition that contains the log files (this example with root partition)
PARTITION="$(mount | grep "on / type" | awk '{print $1}')"
# find the percentage used of the partition
PARTITION_USAGE_PERCENT="$(df -h | grep "$PARTITION" | awk '{print $5}' | sed s/%//g)"
# if partition too full...
if [[ "$PARTITION_USAGE_PERCENT" -gt 85 ]]; then
# run command to delete extra files
printf "%s%s%s\n" "Disk usage is at " "$PARTITION_USAGE_PERCENT" "% deleting log files..."
find /files/logs -type f -mtime 3 -name '*.log' -exec rm {} \;
fi
CodePudding user response:
You can directly give df
a file or directory as argument; it also have a -P
option that makes its output parsable in a portable way:
df -P /files/logs | tail -n 1 | awk '{print $5}' | sed 's/%$//'
remark: you can replace tail -n 1 | awk '{print $5}' | sed 's/%$//'
with awk 'END{sub(/%$/,"",$5);print $5}'
Also, some find
implementations have a -delete
option, but for portability it's better to use -exec rm -f {}
instead:
find /files/logs -type f -mtime 3 -name '*.log' -exec rm -f {}
So to sum it up:
logdir=/files/logs
percentage_used=$(
df -P "$logdir" |
tail -n 1 |
awk '{print $5}' |
sed 's/%$//'
)
if [ "$percentage_used" -gt 80 ]
then
find "$logdir" -type f -mtime 3 -name '*.log' -exec rm -f {}
fi