bash腳本編程:
編程語言:
數據結構
順序執行
選擇執行
條件測試
運行命令或[[ EXPRESSION ]]
執行狀態返回值;
if
case
循環執行
將某代碼段重複運行多次;
重複運行多少次?
循環次數事先已知:
循環次數事先未知;
必須有進入條件和退出條件:
for, while, until
函數:結構化編程及代碼重用;
function
for循環語法:
for NAME in LIST; do
循環體
done
列表生成方式:
(1) 整數列表
{start..end}
$(seq start [[step]end])
(2) glob
/etc/rc.d/rc3.d/K*
(3) 命令
通過ping命令探測172.16.250.1-254範圍內的所有主機的在線狀態;
#!/bin/bash # net='172.16.250' uphosts=0 downhosts=0 for i in {1..20}; do ping -c 1 -w 1 ${net}.${i} &> /dev/null if [ $? -eq 0 ]; then echo "${net}.${i} is up." let uphosts++ else echo "${net}.${i} is down." let downhosts++ fi done echo "Up hosts: $uphosts." echo "Down hosts: $downhosts."
while循環:
while CONDITION; do
循環體
done
CONDITION:循環控制條件;進入循環之前,先做一次判斷;每一次循環之後會再次做判斷;
條件爲“true”,則執行一次循環;直到條件測試狀態爲“false”終止循環;
因此:CONDTION一般應該有循環控制變量;而此變量的值會在循環體不斷地被修正;
示例:求100以內所有正整數之和;
#!/bin/bash # declare -i sum=0 declare -i i=1 while [ $i -le 100 ]; do let sum+=$i let i++ done echo "$i" echo "Summary: $sum."
練習:添加10個用戶
user1-user10 #!/bin/bash # declare -i i=1 declare -i users=0 while [ $i -le 10 ]; do if ! id user$i &> /dev/null; then useradd user$i echo "Add user: user$i." let users++ fi let i++ done echo "Add $users users."
練習:通過ping命令探測172.16.250.1-254範圍內的所有主機的在線狀態;(用while循環)
#!/bin/bash # declare -i i=1 declare -i uphosts=0 declare -i downhosts=0 net='172.16.250' while [ $i -le 20 ]; do if ping -c 1 -w 1 $net.$i &> /dev/null; then echo "$net.$i is up." let uphosts++ else echo "$net.$i is down." let downhosts++ fi let i++ done echo "Up hosts: $uphosts." echo "Down hosts: $downhosts."
練習:打印九九乘法表;(分別使用for和while循環實現)
#!/bin/bash # for j in {1..9}; do for i in $(seq 1 $j); do echo -e -n "${i}X${j}=$[$i*$j]\t" done echo done #!/bin/bash # declare -i i=1 declare -i j=1 while [ $j -le 9 ]; do while [ $i -le $j ]; do echo -e -n "${i}X${j}=$[$i*$j]\t" let i++ done echo let i=1 let j++ done
練習:利用RANDOM生成10個隨機數字,輸出這個10數字,並顯示其中的最大者和最小者;
#!/bin/bash # declare -i max=0 declare -i min=0 declare -i i=1 while [ $i -le 9 ]; do rand=$RANDOM echo $rand if [ $i -eq 1 ]; then max=$rand min=$rand fi if [ $rand -gt $max ]; then max=$rand fi if [ $rand -lt $min ]; then min=$rand fi let i++ done echo "MAX: $max." echo "MIN: $min."