欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

shel  while循環(huán)示例小結

 更新時間:2024年04月22日 10:31:23   作者:MMR.陳  
使用while循環(huán),可以使得用戶重復執(zhí)行一系列操作,直到某個條件的發(fā)生,這篇文章主要介紹了shel while循環(huán),需要的朋友可以參考下

1.基本語法

while [ 條件表達式 ]
do
	語句
	語句
done

示例:循環(huán)輸出 1~10這幾個數(shù)

[root@openEuler ~]# cat while1.sh 
#!/bin/bash
i=1
while [ $i -le 10 ]
do
	echo $i
	let i++
done

示例:使用 exec 讀取指定文件的內(nèi)容并循環(huán)輸出。

# 第一步創(chuàng)建文件及內(nèi)容
[root@openEuler ~]# cat > myfile << EOF
> open
> openlab
> openlab123
> linux
> readhat
> EOF
[root@openEuler ~]# cat myfile 
open
openlab
openlab123
linux
readhat
# 第二步:編寫腳本來實現(xiàn)文件讀取并循環(huán)輸出
[root@openEuler ~]# cat while2.sh 
#!/bin/bash
exec < myfile
while read line
do
	echo $line
done
[root@openEuler ~]# bash while2.sh 
open
openlab
openlab123
linux
readhat

使用另一種方式來讀取文件:

[root@openEuler ~]# cat while3.sh 
#!/bin/bash
while read line
do
	echo $line
done < myfile
[root@openEuler ~]# bash while3.sh 
open
openlab
openlab123
linux
readhat

2.無限循環(huán)

在 while 的表達式中,可以指定以下幾個特殊值:

  • true 它會一直循環(huán),而且它的狀態(tài)返碼是 0
  • false 它不做任何事,表示成功,狀態(tài)碼為 0
  • : 它的作用與 true 相同,都是進行無限循環(huán)

示例:

[root@openEuler ~]# while true ; do echo 123123 ; done   #會一直循環(huán)
[root@openEuler ~]# while false ; do echo 123123 ; done
[root@openEuler ~]# echo $?
0
[root@openEuler ~]# while : ; do echo 123123 ; done

3.使用示例

[root@openEuler ~]# cat while4.sh 
#!/bin/bash
price=$[ $RANDOM % 100 ]
time=0
while true
do
	read -p 'Please enter product price [0-99]: ' input
	let time++
	if [ $input -eq $price ]; then
		echo 'Good luck, you guessed it.'
		echo 'You have guessed $time times.'
		exit 0
	elif [ $input -gt $price ]; then
		echo "$input is to high"
	else
		echo "$input is to low"
	fi
	if [ $time -eq 5 ]; then
		echo "You have guessed is 5 times. exit"
		exit 1
	fi
done
[root@openEuler ~]# bash while4.sh 
Please enter product price [0-99]: 50
50 is to low
Please enter product price [0-99]: 80
80 is to high
Please enter product price [0-99]: 70
70 is to high
Please enter product price [0-99]: 60
60 is to low
Please enter product price [0-99]: 65
65 is to low
You have guessed is 5 times. exit
[root@openEuler ~]# 

示例:使用while讀取文件

# 1. 創(chuàng)建文件
[root@openEuler ~]# cat ips
192.168.72.131  22
192.168.72.132  23
192.168.72.133  22
# 2. 編寫腳本 
[root@openEuler ~]# cat while6.sh 
#!/bin/bash
while read line
do
	IP=`echo $line|cut -d" " -f1`   # 也可以使用awk來實現(xiàn),如:IP=`echo $line|awk '{print $1}'`
	PORT=$(echo $line|cut -d " " -f 2)
	echo "IP:$IP, PORT:${PORT}"
done < ips
# 3. 運行測試
[root@openEuler ~]# bash while6.sh 
IP:192.168.72.131, PORT:22
IP:192.168.72.132, PORT:23
IP:192.168.72.133, PORT:22

到此這篇關于shel while循環(huán)的文章就介紹到這了,更多相關shell while循環(huán)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論