Exemples de lancement du script
Notez qu’il faut lancer en utilisant « source
«
- Supprimer les plus vieux fichiers du dossier courant (
./
) tant qu’il prend plus de 96Mo :source ./clean_custom.sh --path ./ -l 9600000
- Supprimer les plus vieux fichiers du dossier temporaire (
/tmp/
) tant qu’il prend plus de 2Go :source ./clean_custom.sh --path /tmp/ -l 2000000000
Code du script
#!/usr/bin/env bash PATH_TO_CLEAN= NUMBER_FILES_TO_DELETE_EACH_LOOP=1 SIZE_LIMIT=2000000000 # ---------------------------------------------------------------------------- # usage: usage() { echo "Clean directory: while size of a dir > limit, oldest files first." echo "Usage: ${filename} [-p|--path path] [-s|--max-size size] | [-h]" echo " -p|--path: path to clean" echo " -l|--limit: max size for the folder (must be > 0)" echo " -h|--help this help" } # ---------------------------------------------------------------------------- # handling arguments: args=("$@") filename=$(basename -- "$0" | sed 's/\(.*\)\..*/\1/') while [ "$1" != "" ]; do case $1 in -p | --path ) shift # stop if path doesn't exist: if [ ! -d "$1" ]; then echo "Path not found: '$1'" usage return 1 fi PATH_TO_CLEAN=$1 ;; -l | --limit ) shift SIZE_LIMIT=$(echo $1 | bc) if [ $SIZE_LIMIT -le 0 ] then usage return 1 fi ;; -h | --help ) usage return ;; * ) usage return 1 esac shift done [ -z "$PATH_TO_CLEAN" ] && echo "Path empty" && usage && return 1 echo "Cleanin dir: '$PATH_TO_CLEAN', size limit=$SIZE_LIMIT" # ---------------------------------------------------------------------------- # handling arguments: while [ 1 ] do s=$(du -sb $PATH_TO_CLEAN | cut -f1 | bc) if [ $s -gt $SIZE_LIMIT ] then find $PATH_TO_CLEAN -type f -printf '%T+ %p\n' | \ sort -nr | \ tail -$NUMBER_FILES_TO_DELETE_EACH_LOOP | \ cut -d' ' -f 2- | \ xargs -I {} rm -f {} else break fi done return 0