“代码量统计脚本”

概述

本文从一段统计C/C++程序脚本入手,记录shell脚本常用和重要的知识点。

代码量统计程序

文件名称,count_code_line.sh

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
#!/bin/bash

# 统计代码行数 去除空格和注释
# author: by wangxintang

function count_dir()
{
total1=0
for input in $*
do
count=`find $input -name *.c -or -name *.cc -or -name *.cpp -or -name *.h -or -name *.hh -or -name *.sh -or -name Make* |
xargs cat | grep -v -e "^$" -e ^s*//.*$ | wc -l`
# if [[ $count == *[!0-9]* ]];then
# echo "not a number2"
# fi
#echo -e "$input: $count"
res=$[ total1 + count ]
total1=$res
done
#echo res: $res
echo $res
}



if [ $# -eq 0 ];then
echo -e count directory: `pwd`
DIR=`pwd`
ret=`find $input -name *.c -or -name *.cc -or -name *.cpp -or -name *.h -or -name *.hh -or -name *.sh -or -name Make* |
xargs cat | grep -v -e "^$" -e ^s*//.*$ | wc -l`
echo "ret: " $ret
else
res=`count_dir $*`
echo "wangxintang"
echo $r 大专栏  “代码量统计脚本”es
#echo $res

代码解释

使用方式

两种使用方式。

方式一,在程序所在目录,执行

1
./count_code_line.sh

统计当前目录下代码量。

方式二,在程序所在目录,统计其他源代码目录下代码量,例如统计 /home/user/code/。操作方式如下

1
./count_code_line.sh /home/user/code/

逐行解释

  1. #!/bin/bash,在文件第一行,指明使用/bin/bash解释程序,其他行以#开头的语句,表示注释
  2. function count_dir(),定义一个名为count_dir的函数
  3. total1=0,定义变量total1并初始化为0
    4.
    1
    2
    3
    4
    for input in $*
    do
    .....
    done

for循环遍历$*内容,input指示$* 中每一个元素。
$*是一个特殊变量,传递给函数或者shell脚本参数列表。

  1. count=`**`,表示执行”****“中内容,并将返回值保存到count变量
  2. res=$[ total1 + count ] ,求算数和
  3. total1=$res 取res中的值,保存到total1
  4. echo $res 输出res中的值
  5. 1
    2
    3
    if [ $# -eq 0 ];then
    else
    fi

if else 语句

扫描二维码关注公众号,回复: 8313703 查看本文章
  1. [ $# -eq 0 ], 判断$# 是否为0

shell重要知识点

特殊变量

$0 当前脚本的文件名
$n 传递给脚本或函数的参数。是一个数字,表示第几个参数。例如,第一个参数是$1,第二个参数是$2。
$# 传递给脚本或函数的参数个数。
$ 传递给脚本或函数的所有参数。
$@ 传递给脚本或函数的所有参数。被双引号(“”)包含时,与 $
稍有不同,下面将会讲到。
$? 上个命令的退出状态,或函数的返回值。
$$ 当前Shell进程ID。对于 Shell 脚本,就是这些脚本所在的进程ID。

猜你喜欢

转载自www.cnblogs.com/lijianming180/p/12099527.html