shell中的while循环实例

本文介绍如何使用Bash脚本中的while循环来完成多种任务,包括计算1到100的和、打印星号矩阵、逐行读取文本文件内容及按列读取数据。同时提供了一个死循环示例,用于实现菜单功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.利用while循环计算1到100的和:

示例代码1:

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

echo $sum


示例代码2:利用while循环计算1到100之间所有奇数之和

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

echo $sum


示例代码3:利用while循环计算1到100之间所有偶数之和

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

echo $sum


2.利用while循环打印**

示例代码:利用while循环打印一个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


3.使用read结合while循环读取文本文件:

示例代码1:

#!/bin/bash
file=$1                  #将位置参数1的文件名复制给file
if [ $# -lt 1 ];then      #判断用户是否输入了位置参数
  echo "Usage:$0 filepath"
  exit
fi
while read -r line   #从file文件中读取文件内容赋值给line(使用参数r会屏蔽文本中的特殊符号,只做输出不做转译)
do

  echo $line        #输出文件内容

done   <  $file



示例2:按列读取文件内容

#!/bin/bash
file=$1
if [[ $# -lt 1 ]]
then
  echo "Usage: $0 please enter you filepath"
  exit
fi
while read -r  f1 f2 f3    #将文件内容分为三列
do
  echo "file 1:$f1 ===> file 2:$f2 ===> file 3:$f3"   #按列输出文件内容

done < "$file"



4.while循环中的死循环:

示例:利用死循环,让用户做选择,根据客户的选择打印相应结果

#!/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
#根据客户的选择做相应的操作
  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    #暂停循环,提示客户按enter键继续
    ;;
   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


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值