shell学习笔记二则:统计空间

最近测试SD卡,顺便学习了一些shell命令,这里顺便记一下。

第一则,为了防止SD卡空间被占满,需要对空间进行判断并清理文件,下面的脚本显示2种方式,一个是通过百分比,一个是通过文件数,个人认为通过百分比比较好一些。关于脚本的挂载目录、百分比、删除文件个数等参数,根据实际情况修改即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/bin/sh
#前提:已挂载目录
mount_dir=/mnt/sd
percent_in=70
file_del=1000

count_del=1000

percent=`df -h | grep $mount_dir | awk '{print $5}' | tr -d '%'`
dev_file=`df -h | grep $mount_dir | awk '{print $1}'`
file_count=`ls -l $mount_dir | wc -l`

# 当空间占用百分比大于某个指定值时,删除目录前指定的数量
if [ $percent -ge $percent_in ];then
echo "need to remove file! occupy" $percent"%" "of" $dev_file
cd $mount_dir
file=`ls | sort | head -$file_del`
rm $file
cd -
else
echo "no need to remove file"
fi
# 当文件个数达到一定数量时删除前x个文件
if [ $file_count -ge $count_del ];then
echo "need to remove file! occupy total" $count_del "files of" $dev_file
cd $mount_dir
file=`ls | sort | head -$file_del`
rm $file
cd -
else
echo "no need to remove file"
fi

#file=`ls | sort | head -$file_del`
#echo $file

echo "comand complete at"
date
echo "======================================"

第二则,统计命令执行时间(这个功能使用在测试SD卡性能上)。主要涉及到time命令的输出格式以及popen的使用。
time命令默认输出是十分友好的,分别显示了分和秒,但在程序计算时不太“友好”,因而使用-p选项,它直接输出以秒为单位的时间。popen是公司公认的重型武器,一般情况不敢随意使用。测试代码就无所谓了,它主要读取grep得到的时间。另外也涉及到sscanf对浮点数的格式化问题。
脚本实现:

1
2
3
echo "time测试"
time -p sleep 2 2>&1 | tee /tmp/time_log
time=`grep real /tmp/time_log | awk '{print $2}'`

C语言实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void simple_test()
{
char time_str[128] = {0};
float time_f = 0.0;
float speed = 0.0;
system("time -p sleep 2 2>&1 | tee /tmp/time_log");

FILE* fp = NULL;
fp = popen("grep real /tmp/time_log | awk '{print $2}'", "r");
fread(time_str, sizeof(time_str), 1, fp);
pclose(fp);
time_str[strlen(time_str) - 1] = '\0';
sscanf(time_str, "%f", &time_f);
speed = 10.0 / time_f;
printf("time_str: %s time_f: %.2f speed: %.2f\n", time_str, time_f, speed);
}

李迟记于2014年5月9日