shell 开发笔记


shell 开发笔记


Author: Yangkai Wang
wang_yangkai@163.com
转载请注明author,出处.

while 循环

#!/bin/sh

while true; do
echo "haha"
sleep 1
done

for 循环

#!/bin/sh

for i in $(seq 1 10)  
do   
	echo $i
	sleep 1
done


for i in $(seq 1 10)
do
    if [ -e /sys/class/net/eth0 ]
    then
        /sbin/ip link set eth0 up
        echo "eth0 is up"
        break
    else
        echo "eth0 netdev is not found, sleep 0.1 second"
        sleep 0.1
    fi
done


获取当前脚本所在路径

#!/bin/sh
DIR="$( cd "$( dirname "$0"  )" && pwd  )"

echo "shell pwd:$DIR"

判断文件是否存在

# [、]的前后有空格符
if [ -f /path/file ]; then 
     echo "file exist"
else
     echo "file no exist"
fi
 
# 判断链接文件是否存在
if [ -L /path/link ]; then 
    echo "link file exist"
else
    echo "link file no exist"
fi

awk

#!/bin/sh

for i in $(seq 1 1000)  
do
	echo "~~~~~~"
	echo $i

	cat /proc/cpuinfo
	cpu_id=`cat /proc/cpuinfo | grep "processor" | awk '{ if (NR == 1){print $3}}'`
	echo "cpu_id:$cpu_id"

	if [ "$cpu_id" != "0" ];then
		echo "error!"
		sleep 24h
	fi

	sleep 5
done


字符串循环

#!/bin/bash

arr=("a" "b" "c" "d" "d" \
"f" "g" "h" "i" "j")


for CHAR in ${arr[@]}
do 

echo "char:$CHAR"

done



统计文件行数

num=`awk 'END{print NR}' $file`


参数个数判断

if [ $# -ne 2 ]; then
	echo "usage: ./xx.sh <parame> <parame>"
	exit
fi


数值累加

cat $file | awk '{print $1} {tot+=$1} END {print "total:"tot} END {print "total K:"tot/1000}'


统计网络包发送频率

#!/bin/sh

#COUNT_1=$(cat /proc/net/dev | grep eth0 | awk '{print $2}')
COUNT_1=$(ifconfig eth0 | grep "TX packets:" | awk '{print $2}' | awk -F':' '{print $2}')

while true; do
sleep 1

COUNT_2=$(ifconfig eth0 | grep "TX packets:" | awk '{print $2}' | awk -F':' '{print $2}')
echo "TX packets:$COUNT_1"

FREQ=`expr $COUNT_2 - $COUNT_1`
echo -e "TX freq:$FREQ\n"
COUNT_1=$COUNT_2

done


打印进程调度优先级process priority (ps -el)

#!/bin/bash

dir_path="/proc"

for sub_dir in "$dir_path"/*/; do
    if [ "$(ls -A $sub_dir)" ]; then

	if [ -f $sub_dir/stat ]; then
	        file_path=$sub_dir/stat
        	cat "${file_path}" | awk '{print $1,$2,$18}'
	fi
    fi
done


获取中断频率

#!/bin/sh

if [[ $# -ne 1 ]]
then
  echo "Usage: $0 [interrupt number]"
  exit 1
fi

interrupt=$1
count=0

echo -e "int nu:$interrupt\n"

name=$(cat /proc/interrupts | grep "$interrupt:" | awk '{print $9}')
value_1=$(cat /proc/interrupts | grep "$interrupt:" | awk '{print $2}')

while true
do
  sleep 1
  value_2=$(cat /proc/interrupts | grep "$interrupt:" | awk '{print $2}')
  freq=`expr $value_2 - $value_1`
  echo "interrupt nu:$interrupt name:$name count:$value_2 freq:$freq"

  value_1=$value_2
done




免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM