脚本将通过top获取指定运行程序的cpu,内存,进程号,名称信息。
按给定时间间隔循环取样,保存于process.txt内
参数1是要获取的进程名称
参数2是指定间隔时间(秒)
代码:
#!/bin/bash
function IsNumber(){
if [ -z $1 ]; then
# echo "need var!"
return 2
fi
echo $1 | grep -q '[^0-9]'
af1=$?
if [ $af1 -ge 1 ]; then
#this is number,output
# echo "number"
return 0
else
# echo "not number"
return 1
fi
}
> process.txt
if [ -z $1 ]; then
read -p "please input process name:" x
read -p "please input Interval(number):" y
else
x=$1
if [ -z $2 ]; then
read -p "please input Interval(number):" y
else
y=$2
fi
fi
IsNumber $y
if [ $? -gt 0 ]; then
echo "Interval variable is not number ,default will be used !"
echo "It is 2s!"
y=2
fi
flag=5
while sleep $y
do
top -d 2 -n 1 | awk -v var1=$x 'NR>6{if($13==var1)print $2 "\t" $10 "\t" $11 "\t" $13}' >> process.txt
top -d 2 -n 1 | grep $x
flagrun=$?
echo flagrun $flag
if [ $flagrun -gt 0 ]; then
if [ $flag -eq 0 ]; then
echo "process still is not running!will stop!"i
break;
fi
echo "process is not running!will try $flag times !"
let flag--
fi
tail -3 process.txt
done
说明:
1参数1参数2可以运行脚本时给出,否则代码内按提示输入
2.参数2如果输入错误不是数字,则按缺省值2执行
3.参数1代表的进程如果检测不到,会提示并尝试5次,仍未检测到则退出运行