目錄
一. for循環
for定義變量
do使用變量,執行動作
done結束標誌
格式1:
#!/bin/bash
for WESTOS in `seq 2 10`
do
echo $WESTOS
done
格式2:
for WESTOS in 1 2 3
do
echo $WESTOS
done
格式3:
for WESTOS in {10..1}
do
echo $WESTOS
done
格式4:
for ((WESTOS=0;WESTOS<10;WESTOS++))
do
echo $WESTOS
done
腳本練習:
check_host.sh
用此腳本檢測10臺與您當前主機直連主機是否網絡通常
如果網絡通常請顯示主機的ip列表
二. while
while ture#條件爲真
do#條件成立所作循環動作done
三. until
until false##條件爲假
do
#條件不成立所作循環動作
done
四. if
if
then
elif
then
...
else
fi
腳本練習:
check_file.sh
please input filename: file
file is not exist
file is file
file is direcory
此腳本會一直詢問直到用戶輸入exit爲止
五. case
case $1 in
word1|WORD1)
action1
;;
word2|WORD2)
action2
;;
*)
action3
esac
腳本練習
system_watch.sh disk memory upload (每秒顯示)
disk 監控磁盤使用情況
memory 監控內存使用情況
upload 監控啓動負載
六. expect
問題腳本
#!/bin/bash
read -p "what's your name:" NAME
read -p "How old are you: " AGE
read -p "Which objective: " OBJ
read -p "Are you ok? " OK
echo $NAME is $AGE\'s old study $OBJ feel $OK
應答腳本
#!/usr/bin/expect
set timeout 1
set NAME [ lindex $argv 0 ]
set AGE [ lindex $argv 1 ]
set OBJ [ lindex $argv 2 ]
set FEEL [ lindex $argv 3 ]
spawn /mnt/ask.sh
expect {
"name"{ send "$NAME\r";exp_continue }
"old"{ send "$AGE\r";exp_continue }
"objective"{ send "$OBJ\r";exp_continue }
"ok"{ send "$FEEL\r" }
}
expect eof
安裝expect
舉例:
腳本練習
auto_ssh 192.168.0.1 westos
可以自動連接目標主機,當目標主機網絡不通時報錯
七. break,continue,exit
contiue ##終止當此次前循環提前進入下個循環
break ##終止當前所在語句所有動作進行語句外的其他動作
exit ##腳本退出