<>

Chapter 4. Bash for Loop Examples

在 Linux 下我们如何使用 bash 循环重复特定的任务? 我们如何设置使用无限循环? 如何使用三循环控制表达式参数?

'for' 循环是 bash 编程语言的一个语句声明,允许代码重复执行。for 循环被列为循环语句,也就是说它是一个进程内的 bash 脚本循环。

例如,您可以运行5次 Linux 命令或任务, 或读取和处理文件列表供循环使用。for 循环可以用于交互的 shell 或在 shell 脚本中使用。

for 循环语法

数值范围的语法如下:

for VARIABLE in 1 2 3 4 5 .. N
do
	command1
	command2
	commandN
done
#!/bin/bash
for i in 1 2 3 4 5
do
   echo "Welcome $i times"
done
#!/bin/bash
for i in $(seq 1 2 20)
do
   echo "Welcome $i times"
done

3.0+

#!/bin/bash
for i in {1..5}
do
   echo "Welcome $i times"
done

4.0+

#!/bin/bash
echo "Bash version ${BASH_VERSION}..."
for i in {0..10..2}
  do
     echo "Welcome $i times"
 done
for (( EXP1; EXP2; EXP3 ))
do
	command1
	command2
	command3
done
#!/bin/bash
for (( c=1; c<=5; c++ ))
do
	echo "Welcome $c times..."
done
#!/bin/bash
for (( ; ; ))
do
   echo "infinite loops [ hit CTRL+C to stop]"
done
for I in 1 2 3 4 5
do
  statements1      #Executed for all values of ''I'', up to a disaster-condition if any.
  statements2
  if (disaster-condition)
  then
	break       	   #Abandon the loop.
  fi
  statements3          #While good and, no disaster-condition.
done
#!/bin/bash
for file in /etc/*
do
	if [ "${file}" == "/etc/resolv.conf" ]
	then
		countNameservers=$(grep -c nameserver /etc/resolv.conf)
		echo "Total  ${countNameservers} nameservers defined in ${file}"
		break
	fi
done
for I in 1 2 3 4 5
do
  statements1      #Executed for all values of ''I'', up to a disaster-condition if any.
  statements2
  if (condition)
  then
	continue   #Go to next iteration of I in the loop and skip statements3
  fi
  statements3
done
#!/bin/bash
FILES="$@"
for f in $FILES
do
        # if .bak backup file exists, read next file
	if [ -f ${f}.bak ]
	then
		echo "Skiping $f file..."
		continue  # read next file and skip cp command
	fi
        # we are hear means no backup file exists, just use cp command to copy file
	/bin/cp $f $f.bak
done