25 May 2013
改进的 rm
我用 u 盘在多台电脑之间同步资料 (因为有些电脑无法上网),然后在某台能上网的电脑上,插入 u 盘时,每隔一段时间进行一次 rsync,将 u 盘上的内容同步到 Dropbox 文件夹。日子久了,发现 Dropbox 里有很多不需要的临时文件,比如 .xxx.swp、xxx.o、a.out、xxx.ncb、xxx.txt~,散布在各个地方,想一次性删除这些文件,又担心误删,于是写了一个脚本来做这件事情,我取名为 brm,即 baurine rm 的缩写,哈哈!
代码如下:
#!/bin/sh
# name: brm
# author: baurine
# date: 2013/05/24
# if you need to delete many files, and you are afraid to make mistake,
# you can try this.
# step 1, you can use command "brm [path] express" to find out files
# that need to delete, the result will output to console and file named
# Brmfiles under current path.
# in internal, the script use "find path -name express" command to
# search files.
# step 2, you can use "vim Brmfiles" or other editors to edit Brmfiles,
# check whether there are files that don't need to delete, if then
# remove it from Brmfiles.
# step 3, now use "brm -d" to delete files. brm use "rm -f" command to
# delete all files in Brmfiles, then rename Brmfiles to Brmfiles_done.
# use like this:
# brm *.swp
# brm /root/mywork *.swp
# brm -d [Brmfiles]
def_out=Brmfiles
function usage() {
echo "Usage:"
echo " brm [path] express"
echo " brm -d [Brmfiles]"
}
function find_files() {
# find ./ -name *.swp
# find /root/mywork -name *.swp
files_found=$(find $1 -name $2)
if [ -z $files_found ]; then
echo "no files matched!"
else
rm -f $def_out
for file in $files_found
do
echo $file
echo $file >> $def_out
done
echo "$def_out has create!"
fi
}
function rm_files() {
catlog=$1
if [ -z $catlog ];then
catlog=$def_out
fi
if ! [ -e $catlog ];then
echo "$catlog not found"
exit 0
fi
files=$(cat $catlog)
for file in $files
do
if [ -e $file ]; then
echo "rm $file"
rm -f $file
else
echo "not exist: $file"
fi
done
mv -f $catlog ${catlog}_done
}
if [ $# -eq 0 ]; then
usage
elif [ $1 == "-d" ]; then
rm_files $2
elif [ $# -eq 1 ]; then
find_files ./ $1
elif [ $# -eq 2 ]; then
find_files $1 $2
else
usage
fi
2013/06/08 补充:
上面的代码在 Redhat 5.8 运行没问题,今天在 Ubuntu 12.04 上运行时,遇到一些麻烦,两者语法略有差别,要做以下修改:
- 定义函数不再需要 function 关键字,去掉。
- 比较字符串相等不使用「==」,而是「=」,所以
elif [ $1 == "-d" ];
要改成elif [ $1 = "-d" ];
if [ -z $files_found ];
这一句原本写得也不是很严谨,在 Redhat 下不会报错,在 Ubuntu 下会报错,要改成if [ -z "$files_found" ];
Baurine