前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Learn bash for loop in Linux

Learn bash for loop in Linux

作者头像
用户8418197
修改2021-04-03 10:04:49
5.3K0
修改2021-04-03 10:04:49
举报
文章被收录于专栏:howtouselinux

This type of for loop is characterized by counting. The range is specified by a beginning (#1) and ending number (#5). The for loop executes a sequence of commands for each member in a list of items. A representative example in BASH is as follows to display welcome message 5 times with for loop:

代码语言:txt
复制
#!/bin/bash
for i in 1 2 3 4 5
do
   echo "Welcome $i times"
done

Sometimes you may need to set a step value (allowing one to count by two’s or to count backwards for instance). Latest bash version 3.0+ has inbuilt support for setting up ranges:

代码语言:txt
复制
#!/bin/bash
for i in {1..5}
do
   echo "Welcome $i times"
done

This is from Bash For Loop Examples In Linux

Bash v4.0+ has inbuilt support for setting up a step value using {START..END..INCREMENT} syntax:

代码语言:txt
复制
#!/bin/bash
echo "Bash version ${BASH_VERSION}..."
for i in {0..10..2}
  do 
     echo "Welcome $i times"
 done

Sample outputs:

代码语言:txt
复制
Bash version 4.0.33(0)-release...
Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
作者已关闭评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档