一、三种方法
1.exec读取文件


exec <file
sum=0
while read line
do
  cmd
done
  1. cat读取文件
    cat file|while read line
    do
    cmd
    done

推荐用途:
通过awk等三剑客获取文件中的数据后,可以使用这种方法用管道抛给while按行读取

  1. while循环最后加重定向
    while read line
    do
    cmd
    done<file

推荐用途:
直接按行读取文件中的内容时,推荐用此方法
二、案例
读取web日志文件,把日志文件中每行中的访问字节数相加,统计访问总量

cat /server/scripts/c9.sh
#!/bin/bash
sum=0
exec <$1
while read line
do
  size=`echo $line|awk '{print $10}'`
  expr $size + 1 &>/dev/null
  if [ $? -ne 0 ];then
   continue
  fi
  ((sum=sum+$size))
done
echo "${1}:total:${sum}bytes =`echo $((${sum}/1024))`KB"
文档更新时间: 2023-08-09 10:54   作者:月影鹏鹏
IT运维支持-AIWALY-月影工作室