温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Shell中使用while循环

发布时间:2021-05-17 16:44:39 来源:亿速云 阅读:298 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关如何在Shell中使用while循环,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

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

如何在Shell中使用while循环

示例代码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

如何在Shell中使用while循环

示例代码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

如何在Shell中使用while循环

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

如何在Shell中使用while循环

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

如何在Shell中使用while循环

如何在Shell中使用while循环

示例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"

如何在Shell中使用while循环

如何在Shell中使用while循环

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

如何在Shell中使用while循环

关于如何在Shell中使用while循环就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI