Hello and welcome to LQ.
LQ uses vBB so you can use BB tags to make posted code easier readable:
Code:
#!/bin/sh --
#Purpose: delete files/folders until space is freed.
# Unset if no debug is necessary
set -Cvxe
# Whoami?
progn="$0"; progn="${progn//*\//}"
[ $# -ne 0 ] && { echo "${progn}: delete files/folders until space is freed. No args allowed, exiting." > /dev/stderr; exit 127; }
# Set freespace in MB Megabyte 1000x1000 per 'df'.
MAXFREESPACE=20000
# Set directory for oldest files to be deleted from to be deleted no ending slash here!
DELROOT=/home/awaken/bin/new
[ -d "${DELROOT}" ] || { logger "${progn}: no DELROOT, exiting; exit 127; }
# Check diskspace.
freemb() { CURRSPACE=`df . -B MB | awk '/^\// {print $4}'`; FREEDSPACE=${FREEDSPACE//[^0-9]/}; }
# Check oldest file and/or directory.
oldest() { OLDESTFILE=`ls -t --color=no "${DELROOT}" | tail -1`; }
main() {
freemb
if [ $CURRSPACE -lt $MAXFREESPACE ]; then
oldest
echo "rm \(-rf\) -- /${OLDESTFILE}" \
|| { logger "${progn}: in (${FUNCNAME}): Unable to delete "${DELROOT}/${OLDESTFILE}", exiting."; exit 1; }."
sleep 2
main
else
sleep 60
main
fi
}
main
exit 0
What I changed was:
- adding an exit code. Not a hard requirement, but often other apps will (or may in the future) depend on the exit code of a script. Therefore it's a good custom to exit the script in a friendly way.
- set "debugging" on. Often comes in handy to see values expanded.
- use descriptive variable names.
- use UPPERCASE variable names. Not a hard requirement, but makes it easier to read.
- use some minor checks to exit if not configured or on execution error.
- use proper quoting as in integers vs strings.
- use "echo" on "fatal" commands will keep things safe while executing them.
If you're going to expand this, you could use:
- a "trap" to catch signals like CTRL+C and such.
- "getopts" to configure DELROOT from the CLI.
- a more fine-grained way of finding files, say "find" with a printf of epoch plus filename?
And maybe define "free space" as a percentage: "df" output already provides it.
Practically I would never run this script because it does not discriminate between files and dirs. Besides, if a certain dir is deleted the result freeing up more of the occupied disk space than you might expect.
The script had a few problems but other than that it looks OK I think.