書寫一些簡單的shell腳本

1、檢查定時任務是否開啓

[root@shell 2.5]# cat sb01.sh 
#!/bin/bash
. /etc/init.d/functions

service=`ps -ef | grep crond | wc -l`

if [ $service -gt 1 ];then
	echo `action "crond is running" /bin/true`
else
	echo `action "crond is failed" /bin/false`
fi

2、檢查內存是否充足

[root@shell 2.5]# cat sb02.sh 
#!/bin/env bash

n=`free | awk -F ' ' 'NR==2 {print $7} '`

if [ $n -gt 102400 ];then
	echo "內存充足"
	exit
else
	echo "內存不足"
	exit
fi

3、檢查Web網站URL是否正常運行

[root@shell 2.5]# cat sb03.sh 
#!/bin/bash
source /etc/init.d/functions

read -p '請輸入測試域名:' str1

error () {
if [ $# -ne 1 ];then
	echo "只能輸入一個域名"
        exit
fi
}

error $str1

if ! ping -w3 -c1 $str1 &>/dev/null;then
        echo "該網站不存在或網站格式書寫錯誤"
        exit
fi

wget --tries=1 -T 5 $strl &>/dev/null

if [ $? -eq 0 ];then
        echo "正在連接$str1...."
        sleep 1
        action "$1連接正常" /bin/true
else
        echo "正在連接$str1...."
        sleep 1
        action "$str1無法正常通訊" /bin/false
fi

4、rsync服務管理腳本

[root@shell 2.5]# cat sb04.sh 
#!/bin/bash
source /etc/init.d/functions

pid_num=/var/run/rsyncd.pid
choice=$1

start() {
if [ -s "$pid_num" ]
then
	echo "running"
else
	rsync --daemon
fi
}

stop() {
if [ -s "$pid_num" ]
then
	kill `cat $pid_num`
else
	echo "stopped"
fi
} 

restart() {
	stop
	sleep 2
	start
}

case "$choice" in 
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		restart
		;;
	*)
		echo -e "\033[31mUsages: $0 {start|stop|restart} \033[0m"
		exit 1
esac

5、生成數列腳本

[root@shell 2.5]# cat sb05.sh 
#!/bin/bash
source /etc/init.d/functions

num=1
while [ $num -le 10 ]
do
	echo $num
	let num++
done

6、一到一百累加運算

[root@shell 2.5]# cat sb06.sh 
#!/bin/bash
source /etc/init.d/functions

num=1
sum=0
while [ $num -le 100 ]
do
	#echo $num
	((sum=num+sum))
	(( num++ ))
	echo $sum 依次累加結果
done
echo $sum 最終結果

7、隨機生成十個文件(因爲生成名字會出現重複字母很有可能生成不夠)

[root@shell 2.5]# cat lj01.sh 
#!/bin/bash

[ -d /test ] || mkdir -p /test 

a=`date +%N | md5sum | head -c10 | xargs echo | sed -nr "s#(.)#\1 #gp"`
b=$a

eval echo $b
for i in $b
do
	touch /test/$i.html
done

8、隨機生成十個文件

[root@shell 2.5]# cat lj02.sh 
#!/usr/bin/env bash

o=/good
[ -d $o ] || mkdir -p /good

for i in {1..10}
do
	test=`date +%N | md5sum | head -c10 | xargs echo`
	touch $o/$test\_.html
done

9、惡搞腳本,別噴我

[root@shell 2.5]# cat good3.sh 
#!/bin/bash
trap "" HUP INT TSTP

while true
do
read -p "你說誰是豬:"  goodnb
case $goodnb in
        "我是豬")
                echo "對你的確是豬"
                sleep 100
                exit
                ;;
        *)
                echo "呸,你居然說自己不是豬"
esac
done
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章