红联Linux门户
Linux帮助

通过shell脚本删除代码里面定义但未使用的变量

发布时间:2016-08-21 09:30:46来源:linux网站作者:叶子一哥
对于大的工程尤其是测试工程,会有很多的编译告警,尤其是定义但未使用的变量,数量太多修改起来很费时,所以通过脚本解决。
 
首先:先将编译的日志保存下来。
 
例如:gcc -o tets test.c >log.log 2>&1 
 
之后在你编译的目录运行脚本./replace_unused.sh log.log即可。
 
#!/bin/bash
function echoGreenChar()  
{  
printf "\033[1;32;40m$1 \033[0m\n"  
}  
#show help info  
function show_help ()  
{  
echoGreenChar "***************************************************"  
echoGreenChar "*replace_unused.sh filename   *"  
echoGreenChar "***************************************************"  
echoGreenChar "Any suggestion please contact qq:977583818 "  
function replace ()  
{  
rm -r unused  
mkdir -p unused/bak  
#将定义但未使用的变量提取出来  
grep ' unused variable' $1|sort -r |uniq > ./unused/unused.txt   
#从$1文件中提取定义但未使用的变量所在的C文件的名字提取出来 tmp是为了同一个C文件只拷贝一次  
awk -F ":" 'BEGIN{tmp["aaa"]=1}{if(tmp[$1]==1){}else{printf("%s\n", $1);tmp[$1]=1}}' ./unused/unused.txt > ./unused/restore  
#从$1文件中提取定义但未使用的变量所在的行号提取出来  
awk -F ":" 'BEGIN{tmp["aaa"]=1}{if(tmp[$1]==1){}else{printf("cp %s unused/bak\n", $1);tmp[$1]=1} printf("sed -i -e %dd %s\n",$2,$1)}' ./unused/unused.txt > unused/rep.sh  
echoGreenChar "replace sh ok "  
sh unused/rep.sh  
echoGreenChar "replace ok" 
}
#if parameter is null, then show help info  
if [ "$1" == "" ] ; then  
show_help  
exit 0  
fi  
#Judge the file is exit  
if [ -e $1 ] ; then  
replace $1  
else  
echoGreenChar "File does not exist"  
fi  
exit 0
 
本文永久更新地址:http://www.linuxdiyf.com/linux/23486.html