Linux---shell编程总结for循环、while循环,until循环(三)

半世苍凉 提交于 2020-02-04 15:59:35

1、for循环:for循环会将参数一个一个赋给变量var
for循环格式:

for var in 参数
do
	commands
done

例子:

for test in Nevada "New Hampshire" "New Mexico" "New York"
do
	echo "Now going to $test"
done

从变量读取列表:

list="Alabama Alaska Arizona Arkansas Colorado"
list=$list" Connecticut"
for state in $list
do
	echo "Have you ever visited $state?"
done

从命令读取值:

file="states"

for state in $(cat $file)
do
	echo "Visit beautiful $state"
done

2、IFS称为内部字段分隔符,shell脚本是通过这个来进行分割,默认会将空格、制表符和换行符为分隔符
更改IFS字段分隔符:

file="states"

IFS=$'\n'
for state in $(cat $file)
do
	echo "Visit beautiful $state"
done

如果要指定多个IFS字符,格式如:

IFS=$’\n’:;
IFS定义字符解析没有任何限制

3、C语言风格的for循环:

for (( var assigment ; condition ; iteration process ))

例子:

for (( i=1; i <= 10; i++ ))
do
	echo "The next number is $i"
done

定义多个变量(判断结束条件只能有一个):

for (( a=1, b=10; a <= 10; a++, b-- ))
do
	echo "$a-$b"
done

4、while循环只要判断式为真就执行
格式:

while [ 判断式 ]
do
	commands
done

例子:

var1=10
while [ $var1 -gt 0 ]
do
	echo $var1
	var1=$[ $var1 - 1 ]
done

5、until循环:只要判断式为假就执行
格式:

until [ 判断式 ]
do
	command
done

例子:

var1=100

until [ $var1 -eq 0 ]
do
	echo $var1
	var1=$[ $var1 - 25 ]
done

6、嵌套循环:
例子:

for (( a = 1; a <= 3; a++ ))
do
	echo "Starting loop $a:"
	for (( b = 1; b <= 3; b++ ))
	do
		echo "Inside loop $b:" 
	done
done

循环处理/etc/passwd:

IFS.OLD=$IFS
IFS=$'\n'
for entry in $(cat /etc/passwd)
do
	echo "Value is $entry"
	IFS=:
	for value in $entry
	do
		echo " $value"
	done
done

提供另一个命令:cut,-d:指定分隔符,-f:指定第几列,-b 表示字节,-c 表示字符,默认分隔符为制表符
例如:cut -d : -f 2 /etc/passwd cut -d : -b 1-5 /etc/passwd
7、退出循环break命令:用于跳出循环
例子:

for var1 in 1 2 3 4 5 6 7 8 9 10
do
	if [ $var1 -eq 5 ]
	then
		break
	fi
	echo "Iteeration number: $var1"
done
echo "The for loop is completed"

break后面还可以接数字,代表停止的循环层级
例子:

for (( a=1; a<4; a++ ))
do
	echo "Outer loop $a"
	for (( b=1; b<100; b++ ))
	do
		if [ $b -gt 4 ]
		then
			break 2
		fi
		echo " Inner loop: $b"
	done
done

8、暂停某次循环continue
例子:

for (( var1=1; var1<15; var1++ ))
do
	if [ $var1 -gt 5 ] && [ $var1 -lt 10 ]
	then
		continue
	fi
	echo "Iteration number: $var1"
done

continue后接数字也是和break一样
例子:

for (( a = 1; a <= 5; a++ ))
do
	echo "Iteration $a:"
	for (( b = 1; b < 3; b++ ))
	do
		if [ $a -gt 2 ] && [ $a -lt 4 ]
		then
			continue 2 
		fi
		var3=$[ $a * $b ]
		echo "The reault of $a * $b os $var3"
	done
done

9、处理循环的输出,可以在done后面用重定向符号,方便阅读和管理
例子:

for (( a = 1; a < 10; a++ ))
do
	echo "The number is $a"
done > test.txt
echo "The command is finished."

10、实例1:查找可执行的文件,执行一个程序的时候,shell会去PATH环境变量中去找
例子:

IFS=:
for folder in $PATH
do
	echo "$folder:"
	for file in $folder/*
	do
		if [ -x $file ]
		then
			echo " $file"
		fi
	done
done
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!