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