shell study-10day--shell流程控制语句for

1、控制流程语句for

1)for语句格式

for 变量 in 参数列表
do
    命令
done

或者

for 变量 in 参数列表 ; do
    命令
done

注:每次只取一个循环列表的数据,在给下面的代码块。

2)for语句实例

A、直接取值

[root@test ~]# vi for-1.sh
#!/bin/bash
for i in a b c d e
do
        echo test is $i
done
[root@test ~]# sh for-1.sh 
test is a
test is b
test is c
test is d
test is e
[root@test ~]#

B、变量中取值

[root@test ~]# vi for-2.sh
#!/bin/bash
list="a b c d e"
for i in $list
do 
        echo test is $i
done
[root@test ~]# sh for-2.sh 
test is a
test is b
test is c
test is d
test is e
[root@test ~]#

C、从命令中取值

[root@youxi1 ~]# vim d.sh
#!/bin/bash
for i in `head -5 /etc/passwd`
do
 echo $i
done
[root@test ~]# sh for-3.sh 
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
[root@test ~]#

3)自定义shell分隔符

默认情况下,base shell 会以空格、制表符、换行符做为分隔符。通过 IFS 来自定义为分隔符

指定单个字符做分隔符:

IFS=: #以:冒号做分隔符

IFS可以指定单个字符作为分隔符,IFS=:(以冒号作为分隔符);IFS也可以指定多个字符作为分隔符,IFS=\n:;(以反斜杠、n、冒号、分号作为分隔符)。注:在IFS中,$'\n'和$'\t'才是换行符和制表符。

A、实例1

[root@test ~]# vim a.sh
#!/bin/bash
list="a1 a2 b1 b2 \"hello world\""
for i in $list
do
 
 echo $i
done
[root@test ~]# sh a.sh
a1
a2
b1
b2
"hello
world"

B、指定以\n 回车做为 for 语句的分隔符

[root@test ~]# vi for-4.sh
#!/bin/bash
IFS=$'\n'
for i in `head -2  /etc/passwd`
do
echo "$i"
done
[root@test ~]# sh for-4.sh 
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
[root@test ~]#

4)C语言中的for语句

A、语法格式

for ((i=0;i<10;i++))
do
commands
done

B、单个变量循环

[root@test ~]# vi for-5.sh 
#!/bin/bash
for (( i=1 ; i<=3 ; i++ ))
do
echo num is $i
done
[root@test ~]# sh for-5.sh 
num is 1
num is 2
num is 3
[root@test ~]#

Cfor嵌套(多变量)

[root@test ~]# vi for-6.sh
#!/bin/bash
for ((a=1,b=5 ; a<6 ; a++,b--))
do
echo num is $a - $b
done
[root@test ~]# sh for-6.sh 
num is 1 - 9
num is 2 - 8
num is 3 - 7
num is 4 - 6
num is 5 - 5
[root@test ~]#

D、打印三角形

[root@test ~]# vi for-7.sh
#!/bin/bash
for ((i=1;i<5;i++));do
  for ((j=1;j<=i;j++));do
     echo -n '*'
  done
  echo -e "\n"
done
[root@test ~]# sh for-7.sh 
*
 
**
 
***
 
****
 
[root@test ~]#

-e  解释转义字符 
\t tab
\n 回车
\b 删除前一个字符
\a 发出报警声
\033[32m$var\033[0m   32---绿色  31---红色
-n  不换行


个人公众号:

image.png

猜你喜欢

转载自blog.51cto.com/13440764/2575382