Shell编程-For循环
时间:2020-02-23 14:45:07 来源:igfitidea点击:
在本教程中,我们将学习Shell编程中的For循环。
循环用于多次执行一个代码块。
我们使用for循环遍历项目列表。
for语法
for variable in items do # code for each item done
其中,"变量"用于保存多个项目列表中的一个项目。
例1:编写一个Shell脚本,使用for循环从1到5打印
在下面的示例中,我们将使用for循环从1到5打印。
#!/bin/sh for i in 1 2 3 4 5 do echo $i done
$sh example01.sh 1 2 3 4 5
大括号扩展
我们使用括号扩展名{m..n}
来在shell脚本中生成字符串。
例:
{1..5} will give 1 2 3 4 5 {a..f} will give a b c d e f {Z..T} will give Z Y X W V U T {-5..5} will give -5 -4 -3 -2 -1 0 1 2 3 4 5 {A,B,C,D} will give A B C D {A,B,C{1..3},D} will give A B C1 C2 C3 D
例2:编写一个Shell脚本,使用括号扩展和for循环从1到10打印
#!/bin/sh for i in {1..10} do echo $i done
其中," {1..10}"将扩展为" 1 2 3 4 5 6 7 8 9 10"。
例3:编写Shell脚本以使用for循环从A到Z打印
#!/bin/sh for ch in {A..Z} do echo $ch done
示例#4:编写Shell脚本以列出当前目录中的所有文件
在这个例子中,我们将使用*
这是一个特殊字符,它有助于列出当前目录中的所有文件。
#!/bin/sh for f in * do echo $f done
$sh example04.sh example01.sh example02.sh example03.sh example04.sh
seq命令
我们使用seq命令生成数字序列。
例:
seq LAST so, seq 5 will give 1 2 3 4 5 seq FIRST LAST so, seq 7 10 will give 7 8 9 10 seq FIRST INCREMENT LAST so, seq 1 2 10 will give 1 3 5 7 9
Example#5:编写一个Shell脚本来打印从1到10的所有奇数
为此,我们可以使用seq命令并将FIRST设置为1,INCREMENT设置为2,LAST设置为10。
#!/bin/sh for i in $(seq 1 2 10) do echo $i done
$sh example05.sh 1 3 5 7 9
对于像C这样的循环编程
以下是在Shell脚本中创建for循环的语法,该语法看起来与C编程中的for循环类似。
for (( var=val; var<=val2; var++ )) do # body of for loop done
Example#6:编写Shell脚本以使用C样式进行循环从1到5打印
#!/bin/sh for(( i = 1; i <= 5; i++ )) do echo $i done
$sh example06.sh 1 2 3 4 5
嵌套循环
我们可以将一个for循环嵌套在另一个循环中。
for var_outer in list_outer do # outer for loop body for var_inner in list_inner do # inner for loop body done done
Example#7:编写一个Shell脚本来打印以下模式
1 1 2 1 2 3 1 2 3 4
为了实现这一点,我们将使用嵌套的for循环。
第一个循环将帮助管理行,第二个循环将帮助打印每行数字。
#!/bin/sh for r in {1..4} do for i in $(seq 1 $r) do printf "$i " done printf "\n" done
在上面的代码中,我们使用printf,它有助于在终端中打印结果。