糖尿病康复,内容丰富有趣,生活中的好帮手!
糖尿病康复 > shell学习笔记二则:统计空间

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

时间:2021-07-01 21:57:22

相关推荐

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

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

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

#!/bin/sh#前提:已挂载目录mount_dir=/mnt/sdpercent_in=70file_del=1000count_del=1000percent=`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 ];thenecho "need to remove file! occupy" $percent"%" "of" $dev_filecd $mount_dirfile=`ls | sort | head -$file_del`rm $filecd -elseecho "no need to remove file"fi# 当文件个数达到一定数量时删除前x个文件if [ $file_count -ge $count_del ];thenecho "need to remove file! occupy total" $count_del "files of" $dev_filecd $mount_dirfile=`ls | sort | head -$file_del`rm $filecd -elseecho "no need to remove file"fi#file=`ls | sort | head -$file_del`#echo $fileecho "comand complete at" dateecho "======================================"

第二则,统计命令执行时间(这个功能使用在测试SD卡性能上)。主要涉及到time命令的输出格式以及popen的使用。

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

脚本实现:

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

C语言实现:

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);}

李迟记于5月9日

如果觉得《shell学习笔记二则:统计空间》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。