Linux Shell指令碼程式設計while語句案例

ghostwu發表於2018-06-01

1,每隔3秒,列印一次系統負載

#!/bin/bash

while true
do
    uptime
    sleep 3
done

2,把監控結果儲存到檔案,在後臺執行,然後用tail -f監控檔案變化

ghostwu@dev:~/linux/shell/flow_control$ sh while.sh &
[1] 12867
#!/bin/bash

while true
do
    uptime >> log.txt
    sleep 3
done
ghostwu@dev:~/linux/shell/flow_control$ tail -f log.txt 
 06:14:32 up 33 min,  1 user,  load average: 0.33, 0.35, 0.32
 06:14:35 up 33 min,  1 user,  load average: 0.33, 0.35, 0.32
 06:14:38 up 33 min,  1 user,  load average: 0.31, 0.34, 0
...

3,程式排程相關命令

fg: 把當前指令碼或者任務放到前臺執行。如果指定某個任務:fg 任務編號。 任務編號通過jobs查詢

bg: 把任務放到後臺執行

jobs:檢視當前執行的指令碼或者任務

ctrl+z:暫停執行當前的指令碼

sh while1.sh & : 加上&,表示後臺執行指令碼

ghostwu@dev:~/linux/shell/flow_control$ fg
sh while.sh
^Z
[1]+  Stopped                 sh while.sh
ghostwu@dev:~/linux/shell/flow_control$ jobs
[1]+  Stopped                 sh while.sh
ghostwu@dev:~/linux/shell/flow_control$ bg
[1]+ sh while.sh &
ghostwu@dev:~/linux/shell/flow_control$ jobs
[1]+  Running                 sh while.sh &
ghostwu@dev:~/linux/shell/flow_control$ sh while.sh &
[2] 13411
ghostwu@dev:~/linux/shell/flow_control$ jobs
[1]-  Running                 sh while.sh &
[2]+  Running                 sh while.sh &
ghostwu@dev:~/linux/shell/flow_control$ fg
sh while.sh
^Z
[2]+  Stopped                 sh while.sh
ghostwu@dev:~/linux/shell/flow_control$ bg
[2]+ sh while.sh &
ghostwu@dev:~/linux/shell/flow_control$ jobs
[1]-  Running                 sh while.sh &
[2]+  Running                 sh while.sh &

 4,用while迴圈列印0, 1, 2, 3, 4

#!/bin/bash
i=0
while [ $i -lt 5 ]
do
    echo $i
    (( i++ ))
done

兩個中括號也可以

#!/bin/bash
i=0
while [[ $i -lt 5 ]]
do
    echo $i
    (( i++ ))
done

還可以用計算表示式

#!/bin/bash
i=0
while (( i < 5 ))
do
    echo $i
    (( i++ ))
done

5,計算1….100的和

ghostwu@dev:~/linux/shell/flow_control$ sh sum.sh 
1+2+3..+100=5050
ghostwu@dev:~/linux/shell/flow_control$ cat sum.sh 
#!/bin/bash

i=1
sum=0
while (( i <= 100 ))
do
    (( sum = sum + i ))
    (( i++ ))
done
echo "1+2+3..+100="${sum}

 6,猜數字

#!/usr/bin/bash

sum=$((RANDOM%51))

echo "需要你猜的數是:"$sum

sleep 1

echo "請輸入1-50之間的數,開始猜吧!"

count=0

function type_num(){
    read -p "請輸入一個數吧:" n
    expr $n + 1 &>/dev/null
    if [ $? -ne 0 ]; then
        echo "請輸入一個數字"
        type_num
    fi
}

function guess(){
    (( count++ ))
    if [ $n -eq $sum ]; then
        echo "你猜中了,你的次數是:"${count}
        if [ $count -lt 3 ]; then
            echo "你太厲害了"
        elif [ $count -ge 3 -a $count -lt 6 ]; then
            echo "還是不錯的,加油"
        else
            echo "你有點水啊"
        fi
        exit 0
    elif [ $n -gt $sum ]; then
        echo "猜大了"
        type_num
    else
        echo "猜小了"
        type_num
    fi
}

function main(){
    type_num
    while true
    do
        guess
    done
}

main

 

相關文章