Is there a smart way to execute a script when disk space is low? I know I can manually check disk space, but it seems like a common problem to want to delete log files when disk space is low (for example) which is what I want to do.


If you are not specifically concerned about your log files, you could put a script to check the disk space in the cron.

Automatically clearing old logs is what logrotate is for.

  • Oh, I didn't know logrotate was actually a a command. I thought that was implemented in the application logic. That's the closest thing to what I'm looking for so I'm marking this correct for now. Though still, if anyone has another solution that can invoke a script on low disk space to clean up specific directories that only me the user knows about that would be even better. – Sridhar Sarnobat Apr 22 '14 at 2:44

You can use df and a one-line shell script.

First, we need to tell df to only print the percentage used:

df / --output='pcent'

Combine this with grep to get the raw number:

df / --output='pcent' | grep -o [0-9]*

This will yield e.g. "55" if the disk has been filled by 55%.

Now in the crontab, we can use it like this:

@daily sh -c "if [ $(df / --output='pcent' | grep -o [0-9]*) -gt 90 ]; then docker system prune -af; fi

In this example, we run docker system prune -af if the disk has been filled by more than 90%. Adjust as needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.