七、Shell脚本高级编程实战第七部
一、写网络服务的系统启动脚本
利用case语句开发类似系统启动rsync服务的脚本
代码:
#!/bin/sah
. /etc/init.d/functions
pidfile="/var/run/rsyncd.pid"
start_rsync(){
if [ -f "$pidfile" ]
then
echo "rsync is running"
else
rsync --daemon
action "rsync is started" /bin/true
fi
}
stop_rsync(){
if [ -f "$pidfile" -a -n "$pidfile" ]
then
kill -USR2 `cat $pidfile`
rm -f ${pidfile}
action "rsync is stopped" /bin/true
else
action "rsync have already been rstopped" /bin/false
fi
}
. /etc/init.d/functions
pidfile="/var/run/rsyncd.pid"
start_rsync(){
if [ -f "$pidfile" ]
then
echo "rsync is running"
else
rsync --daemon
action "rsync is started" /bin/true
fi
}
stop_rsync(){
if [ -f "$pidfile" -a -n "$pidfile" ]
then
kill -USR2 `cat $pidfile`
rm -f ${pidfile}
action "rsync is stopped" /bin/true
else
action "rsync have already been rstopped" /bin/false
fi
}
case "$1" in
start)
start_rsync
RETVAL=$?
;;
stop)
stop_rsync
RETVAL=$?
;;
restart)
stop_rsync
sleep 10
start_rsync
RETVAL=$?
;;
*)
echo "USAGE: $0 {start|stop|restart}"
exit 1
;;
esac
exit $RETVAL
start)
start_rsync
RETVAL=$?
;;
stop)
stop_rsync
RETVAL=$?
;;
restart)
stop_rsync
sleep 10
start_rsync
RETVAL=$?
;;
*)
echo "USAGE: $0 {start|stop|restart}"
exit 1
;;
esac
exit $RETVAL
测试:
二、进程管理的命令
fg 放到前台执行
bg 放到后台执行,ctrl+z表示暂停当前会话
jobs 当前后台执行的任务
strace 跟踪一个进程的系统调用,top 显示进程
三、while循环,1加到100之和
#!/bin/sh
i=1
sum=0
while [ $i -le 100 ]
do
let sum=sum+i;
let i=i+1
done
echo "$sum"
1.let效果是小于(())
2.首项+末项的和乘以项数/2,如果计算1000万,这种算法效率更高,所以算法很重要,用上面的方法就是有问题的
四、while循环,打印10,9,8,7.。。。1
#!/bin/sh
i=10
while ((i>0))
do
echo $i
((i--))
sleep 1
done
五、计算apache一天的日志access_xxx.log中所有行的日志各个元素的访问字节数总和。
#!/bin/sh
sum=0
i=0
while read line
do
i=$(echo $line|awk '{print $(10)}')
if expr $i + 0 &>/dev/null
then
((sum=sum+i))
fi
done < /server/scripts/access.log
sum=0
i=0
while read line
do
i=$(echo $line|awk '{print $(10)}')
if expr $i + 0 &>/dev/null
then
((sum=sum+i))
fi
done < /server/scripts/access.log
echo $sum
while小结:while擅长1分钟以内的循环处理
六、打印5,4,3,2,1用for循环
#!/bin/sh
for n in 5 4 3 2 1
do
echo $n
sleep 1
done
七、用for设置开机自启动:crond rsyslog network sshd network nfs rpcbind mysqld
#!/bin/sh
for name in `chkconfig --list|grep 3:on|awk '{print $1}'`
do
chkconfig $name off
done
for name in `chkconfig --list|grep 3:on|awk '{print $1}'`
do
chkconfig $name off
done
for name in crond rsyslog network sshd network nfs rpcbind mysqld
do
chkconfig $name on
done
do
chkconfig $name on
done