Shell script to count files, then remove oldest files

后端 未结 11 2243
眼角桃花
眼角桃花 2021-01-30 05:29

I am new to shell scripting, so I need some help here. I have a directory that fills up with backups. If I have more than 10 backup files, I would like to remove the oldest fi

11条回答
  •  醉酒成梦
    2021-01-30 05:50

    On a very limited chroot environment, we had only a couple of programs available to achieve what was initially asked. We solved it that way:

    MIN_FILES=5
    FILE_COUNT=$(ls -l | grep -c ^d )
    
    
    if [ $MIN_FILES -lt $FILE_COUNT  ]; then
      while [ $MIN_FILES -lt $FILE_COUNT ]; do
        FILE_COUNT=$[$FILE_COUNT-1]
        FILE_TO_DEL=$(ls -t | tail -n1)
        # be careful with this one
        rm -rf "$FILE_TO_DEL"
      done
    fi
    

    Explanation:

    • FILE_COUNT=$(ls -l | grep -c ^d ) counts all files in the current folder. Instead of grep we could use also wc -l but wc was not installed on that host.
    • FILE_COUNT=$[$FILE_COUNT-1] update the current $FILE_COUNT
    • FILE_TO_DEL=$(ls -t | tail -n1) Save the oldest file name in the $FILE_TO_DEL variable. tail -n1 returns the last element in the list.

提交回复
热议问题