[英]How to create a script in Linux to delete all files from the directory expect only left 5 files
How to create a script in Linux to delete all files from the directory Condition:- If in the directory only 5 files are left then should not delete any files from that directory.如何在 Linux 中创建脚本以删除目录中的所有文件条件:- 如果目录中只剩下 5 个文件,则不应从该目录中删除任何文件。
#! /bin/bash
myPath="/tmp"
myFileList=$(find $myPath -maxdepth 1 -type f)
num=0
for candidate in $myFileList
do
num=$(($num + 1))
if [[ $num -le 5 ]]
then
echo "do not delete: $num"
continue
fi
echo "number $num: delete $candidate"
# remove the followong comment sign if you want the script to remove the file
# rm $candidate
done
to fix the problem with spaces in filenames change setting of 'IFS' shell variable before the for-loop:解决文件名中的空格问题,在 for 循环之前更改 'IFS' shell 变量的设置:
#! /bin/bash
myPath="/tmp"
myFileList=$(find $myPath -maxdepth 1 -type f -printf "%T@ %p\n" |sort -rn|awk '1 {$1=""; print $0;}')
num=0
OIFS="$IFS"
IFS=$'\n'
for candidate in $myFileList
do
num=$(($num + 1))
if [[ $num -le 5 ]]
then
echo "do not delete: $num \"$candidate\""
continue
fi
echo "number $num: delete $candidate"
# remove the followong comment sign if you want the script to remove the file
# rm $candidate
done
IFS="$OIFS"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.