核心代码:
先取出所有的状态码,再筛选1-5开头的状态码
cat ${nginx_log_path} | grep -ioE "HTTP\/1\.[1|0]\"[[:blank:]][0-9]{3}"| awk '{print $2}' > ${nginx_log_awkpath}
注意: linux命令行用 echo -e "\033[31m 文字内容 \033[0m" 标红文字内容,但是再shell脚本中,不需要-e,直接echo "\033[31m 文字内容 \033[0m"
先取出所有的状态码,再筛选1-5开头的状态码
cat ${nginx_log_path} | grep -ioE "HTTP\/1\.[1|0]\"[[:blank:]][0-9]{3}"| awk '{print $2}' > ${nginx_log_awkpath}
http_code_100=$(grep -o '1[0-9][0-9]' ${nginx_log_awkpath} | wc -l)
法1:
#!/bin/bash
nginx_log_path='/usr/local/var/log/nginx//access.log'
nginx_log_awkpath='/usr/local/nginx/logs/mynginx.log'
cat ${nginx_log_path} | grep -ioE "HTTP\/1\.[1|0]\"[[:blank:]][0-9]{3}"| awk '{print $2}' > ${nginx_log_awkpath}
echoFun(){
echo "\033[31m $1 \033[0m" $2
}
check_http_status(){
http_code_100=$(grep -o '1[0-9][0-9]' ${nginx_log_awkpath} | wc -l)
http_code_200=$(grep -o '2[0-9][0-9]' ${nginx_log_awkpath} | wc -l)
http_code_300=$(grep -o '3[0-9][0-9]' ${nginx_log_awkpath} | wc -l)
http_code_400=$(grep -o '4[0-9][0-9]' ${nginx_log_awkpath} | wc -l)
http_code_500=$(grep -o '5[0-9][0-9]' ${nginx_log_awkpath} | wc -l)
http_code_total=$(grep -o '[1-5][0-9][0-9]' ${nginx_log_awkpath} | wc -l)
echoFun "http status[100+]" "${http_code_100}"
echoFun "http status[200+]" "${http_code_200}"
echoFun "http status[300+]" "${http_code_300}"
echoFun "http status[400+]" "${http_code_400}"
echoFun "http status[500+]" "${http_code_500}"
echoFun "http status total" "${http_code_total}"
}
check_http_status
法2:
#!/bin/bash
nginx_log_path='/usr/local/var/log/nginx/access.log'
echoFun(){
echo "\033[31m $1 \033[0m" $2
}
check_http_status(){
http_status_codes=(`cat ${nginx_log_path} | grep -ioE "HTTP\/1\.[1|0]\"[[:blank:]][0-9]{3}" | awk '{
if($2>=100 && $2<200){
i++
}else if($2>=200 && $2<300){
j++
}else if($2>=300 && $2<400){
k++
}else if($2>=400 && $2<500){
l++
}else if($2>=500){
m++
}
}END{
print i?i:0,j?j:0,k?k:0,l?l:0,m?m:0,i+j+k+l+m
}'
`)
echoFun "http status[100+]" "${http_status_codes[0]}"
echoFun "http status[200+]" "${http_status_codes[1]}"
echoFun "http status[300+]" "${http_status_codes[2]}"
echoFun "http status[400+]" "${http_status_codes[3]}"
echoFun "http status[500+]" "${http_status_codes[4]}"
}
check_http_status
注意: linux命令行用 echo -e "\033[31m 文字内容 \033[0m" 标红文字内容,但是再shell脚本中,不需要-e,直接echo "\033[31m 文字内容 \033[0m"
关于echo 不同颜色标亮文字的用法详见:http://blog.51cto.com/onlyzq/546459
格式如下: echo -e "\033[字背景颜色;文字颜色m字符串\033[0m"