Linux Shell脚本编程while语句案例

时间:2021-12-06 04:24:11

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