for循环

时间:2019-04-16 23:59:05  来源:igfitidea点击:

Bash shell可以一次又一次地重复特定的指令,直到满足特定的条件。一组重复执行的指令称为循环。

Bash支持for循环和while循环

每一个循环必须:

  1. 首先,必须初始化循环条件中使用的变量,然后开始执行循环。
  2. 在每次迭代的开始都要进行条件测试。
  3. 循环体以一条修改test (条件)变量值的语句结束。
  4. 重复执行某一个语句块。

shell for 循环语法

for var in item1 item2 ... itemN
do
        command1
        command2
        ....
        ...
        commandN
done

shell for循环遍历数字列表语法:

for var in list-of-values
do
        command1
        command2
        ....
        ...
        commandN
done

shell for循环遍历文件列表语法:

for var in file1 file2 file3 fileN
do
        command1
        command2
        ....
        ...
        commandN
done

shell for循环遍历文件内容的语法:

for var in $fileNames
do
        command1
        command2
        ....
        ...
        commandN
done

shell for循环进行命令替换语法:

for var in $(Linux-command-name)
do
        command1
        command2
        ....
        ...
        commandN
done

shell for循环遍历数组语法:

# define an array   
ArrayName=(~/.config/*.conf)
for var in "${ArrayName[@]}" 
do
        command1 on $var
        command2
        ....
        ...
        commandN
done

shell for循环三个表达式语法,类似c语言:

for (( EXP1; EXP2; EXP3 ))
do
	command1
	command2
	command3
done

EXP1用于初始化,EXP2用于测试条件,EXP3用于修改条件的变量值。

for循环对指定列表(item1…itemN)中赋给var(变量)的每个新值执行一次命令行,直到条件不满足为止。列表或者值通常为:

  • 字符串
  • 数字
  • 命令行参数
  • 文件名
  • Linux命令输出

示例

shell for循环遍历数字列表:

#!/bin/bash
for i in 1 2 3 4 5
do
  echo "Welcome $i times."
done

或者使用范围值

#!/bin/bash
for i in {1..10}
do
	echo "$n * $i = $(( $i * $n))"
done

shell for循环遍历字符串列表:

#!/bin/bash
# A simple shell script to print list of cars
for car in bmw ford toyota nissan
   do
   echo "Value of car is: $car"
done

shell for循环将字符串转换为命令:

#!/bin/bash
# A simple shell script to run commands 
for command in date pwd df 
   do
   echo
   echo "*** The output of $command command >"
   #run command 
   $command
   echo
done

shell for循环遍历参数的内容:

#!/bin/bash
# A shell script to verify user password database
files="/etc/passwd /etc/group /etc/shadow /etc/gshdow"
for f in $files
do
	[  -f $f ] && echo "$f file found" || echo "*** Error - $f file missing."
done

shell for循环遍历目录下所有文件:

#!/bin/bash
echo "Printing file names in /tmp directory:"
for f in $(ls /tmp/*)
do
	echo $f
done