简体   繁体   中英

Monitor disk space in an `until` loop

my first question here. Hope it's a good one.

So I'm hoping to create a script that kills another script running arecord when my disk gets to a certain usage. (I should point out, I'm not exactly sure how I got to that df filter... just kinda searched around...) My plan is to run both scripts (the one recording, and the one monitoring disk usage) in separate screen s.

I'm doing this all on a Raspberry Pi, btw.

So this is my code so far:

#!/bin/bash

DISK=$(df / | grep / | awk '{ print $5}' | sed 's/%//g')

until [ $DISK -ge 50 ]
    do
        sleep 1
    done

killall arecord

This code works when I play with the starting value ("50" changed to "30" or so). But it doesn't seem to "monitor" my disk the way I want it to. I have a bit of an idea what's going on: the variable DISK is only assigned once, not checked or redefined periodically.

In other words, I probably want something in my until loop that "gets" the disk usage from df , right? What are some good ways of going about it?

=

PS I'd be super interested in hearing how I might incorporate this whole script's purpose into the script running arecord itself, but that's beyond me right now... and another question...

You are only setting DISK once since it's done before the loop starts and not done as part of the looping process.

A simple fix is to incorporate the evaluation of the disk space into the actual while loop itself, something like:

#!/bin/bash
until [ $(df / | awk 'NR==2 {print $5}' | tr -d '%') -ge 50 ] ; do
    sleep 1
done
killall arecord

You'll notice I've made some minor mods to the command as well, specifically:

  • You can use awk itself to get the relevant line from the ps output, no need to use grep in a separate pipeline stage.
  • I prefer tr for deleting single characters, sed can do it but it's a bit of overkill.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM