溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何在Shell中使用while循環(huán)

發(fā)布時(shí)間:2021-05-17 16:44:39 來(lái)源:億速云 閱讀:303 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)如何在Shell中使用while循環(huán),文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

1.利用while循環(huán)計(jì)算1到100的和:

示例代碼1:

#!/bin/bash
i=1
sum=0
while [ $i -le 100 ]
do
 let sum=sum+$i
 let i++
done
echo $sum

如何在Shell中使用while循環(huán)

示例代碼2:利用while循環(huán)計(jì)算1到100之間所有奇數(shù)之和

#!/bin/bash
i=1
sum=0
while [ $i -le 100 ]
do
 let sum=sum+$i
 let i+=2
done
echo $sum

如何在Shell中使用while循環(huán)

示例代碼3:利用while循環(huán)計(jì)算1到100之間所有偶數(shù)之和

#!/bin/bash
i=2
sum=0
while [ $i -le 100 ]
do
 let sum=sum+$i
 let i+=2
done
echo $sum

如何在Shell中使用while循環(huán)

2.利用while循環(huán)打印**

示例代碼:利用while循環(huán)打印一個(gè)5x5的*

#!/bin/bash
i=1
j=1
while [ $i -le 5 ]
do
 while [ $j -le 5 ]
 do
   echo -n "* "
   let j++
 done
 echo
 let i++
 let j=1
done

如何在Shell中使用while循環(huán)

3.使用read結(jié)合while循環(huán)讀取文本文件:

示例代碼1:

#!/bin/bash
file=$1         #將位置參數(shù)1的文件名復(fù)制給file
if [ $# -lt 1 ];then   #判斷用戶是否輸入了位置參數(shù)
 echo "Usage:$0 filepath"
 exit
fi
while read -r line  #從file文件中讀取文件內(nèi)容賦值給line(使用參數(shù)r會(huì)屏蔽文本中的特殊符號(hào),只做輸出不做轉(zhuǎn)譯)
do
 echo $line    #輸出文件內(nèi)容
done  < $file

如何在Shell中使用while循環(huán)

如何在Shell中使用while循環(huán)

示例2:按列讀取文件內(nèi)容

#!/bin/bash
file=$1
if [[ $# -lt 1 ]]
then
 echo "Usage: $0 please enter you filepath"
 exit
fi
while read -r f1 f2 f3  #將文件內(nèi)容分為三列
do
 echo "file 1:$f1 ===> file 2:$f2 ===> file 3:$f3"  #按列輸出文件內(nèi)容
done < "$file"

如何在Shell中使用while循環(huán)

如何在Shell中使用while循環(huán)

4.while循環(huán)中的死循環(huán):

示例:利用死循環(huán),讓用戶做選擇,根據(jù)客戶的選擇打印相應(yīng)結(jié)果

#!/bin/bash
#打印菜單
while :
do
 echo "********************"
 echo "    menu    "
 echo "1.tima and date"
 echo "2.system info"
 echo "3.uesrs are doing"
 echo "4.exit"
 echo "********************"
 read -p "enter you choice [1-4]:" choice
#根據(jù)客戶的選擇做相應(yīng)的操作
 case $choice in
  1)
  echo "today is `date +%Y-%m-%d`"
  echo "time is `date +%H:%M:%S`"
  read -p "press [enter] key to continue..." Key  #暫停循環(huán),提示客戶按enter鍵繼續(xù)
  ;;
  2)
  uname -r
  read -p "press [enter] key to continue..." Key
  ;;
  3)
  w
  read -p "press [enter] key to continue..." Key
  ;;
  4)
  echo "Bye!"
  exit 0
  ;;
  *)
  echo "error"
  read -p "press [enter] key to continue..." Key
  ;;
 esac
done

如何在Shell中使用while循環(huán)

關(guān)于如何在Shell中使用while循環(huán)就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI