循环
嵌套循环处理文件数据
#! /bin/bash IFS=$'\n' for entry in $(cat /etc/passwd) do echo "Values in $entry" IFS=':' for value in $entry do echo $value done done Values in root:x:0:0:root:/root:/bin/bash root x 0 0 root /root /bin/bash
break跳出内部循环
[root@iZbp11f8g5h7oozejqy6k6Z shell]# sh test7.sh Outer loop:1 Inner loop:1 Inner loop:2 Inner loop:3 Inner loop:4 Outer loop:2 Inner loop:1 Inner loop:2 Inner loop:3 Inner loop:4 Outer loop:3 Inner loop:1 Inner loop:2 Inner loop:3 Inner loop:4 [root@iZbp11f8g5h7oozejqy6k6Z shell]# cat test7.sh #! /bin/bash for (( a = 1; a < 4; a++)) do echo "Outer loop:$a" for (( b = 1; b < 100; b++)) do if [ $b -eq 5 ] then break fi echo " Inner loop:$b" done done
break跳出外部循环
break n
n指定了要跳出的循环层级
[root@iZbp11f8g5h7oozejqy6k6Z shell]# sh test7.sh Outer loop:1 Inner loop:1 Inner loop:2 Inner loop:3 Inner loop:4 [root@iZbp11f8g5h7oozejqy6k6Z shell]# cat test7.sh #! /bin/bash for (( a = 1; a < 4; a++)) do echo "Outer loop:$a" for (( b = 1; b < 100; b++)) do if [ $b -eq 5 ] then break 2 fi echo " Inner loop:$b" done done
创建多个账户
[root@iZbp11f8g5h7oozejqy6k6Z shell]# sh test9.sh adding rich adding chrinstine adding barbara adding tim [root@iZbp11f8g5h7oozejqy6k6Z shell]# cat test9.sh #! /bin/bash while IFS=',' read -r userid name do echo "adding $userid" useradd -c "$name" -m $userid done < user.txt [root@iZbp11f8g5h7oozejqy6k6Z shell]# cat user.txt rich,Richard Blum chrinstine,Christine Bresnahan barbara,Barbara Blum tim,Timothy Bresnahan
[root@iZbp11f8g5h7oozejqy6k6Z shell]# tail -n 4 /etc/passwd rich:x:1001:1001:Richard Blum:/home/rich:/bin/bash chrinstine:x:1002:1002:Christine Bresnahan:/home/chrinstine:/bin/bash barbara:x:1003:1003:Barbara Blum:/home/barbara:/bin/bash tim:x:1004:1004:Timothy Bresnahan:/home/tim:/bin/bash