循环语句之for循环
for 变量 in 取值列表 do 循环体 done 但条件为真,则执行循环体,如果条件为假,则结束循环。 #取值列表,很多种取值方法,默认以空白字符为分隔符 [root@shell01 scripts]# vim for-1.sh #!/bin/bash for i in file1 file2 file3 do echo "$i" done [root@shell01 scripts]# sh for-1.sh file1 file2 file3 #取值列表出现空格,要用引号。特殊字符要用转义字符 [root@shell01 scripts]# vim for-2.sh #!/bin/bash for i in 'file1 test' \( file2 file3 #file1 test是一个字符串,用单引号/双引号包起来。\转义 do echo "$i" done #根据变量进行取值 [root@shell01 scripts]# vim for-3.sh #!/bin/bash List="file1 file2 file3" for i in $List do echo "$i" done #通过命令取值 [root@shell01 scripts]# vim for-4.sh #!/bin/bash for i in $(cat /etc/hosts) do echo "$i" done #自定义分隔符 IFS=: #以冒号为分隔符 [root@shell01 scripts]# vim for-5.sh #!/bin/bash IFS=: for i in $(cat /etc/passwd | head -1) do echo "$i" done #指定多个分隔符 IFS=':;/' #这里有特殊字符,要用引号引起来 [root@shell01 scripts]# vim for-6.sh #!/bin/bash IFS=':;/' #这里有特殊字符,要用引号引起来 for i in $(cat test.txt) do echo $i done #以换行符作为分隔符 IFS=$'\n' [root@shell01 scripts]# vim for-7.sh #!/bin/bash IFS=$'\n' for i in $(cat /etc/hosts) do echo $i done #C语言风格的for (了解) [root@shell01 scripts]# vim for-8.sh #!/bin/bash for i in {1..10} do echo $i done [root@shell01 scripts]# vim for-8.sh #!/bin/bash for ((i=0;i<10;i++)) #C语言格式,用双括号 do echo $i done #定义多个变量,输入1-9的升序和降序 #C语言风格 for ((a=1,b=9;a<10;a++,b--)) do echo $a $b done #正常怎么写 a=0 b=10 for i in {1..9} do let a++ let b-- echo $a $b done
标签:Shell,05,sh,shell01,循环,done,scripts,vim,root From: https://www.cnblogs.com/ludingchao/p/18220242