关于循环的总结

2021-07-27 18:04:42 浏览数 (1)

for

数字型

代码语言:javascript复制
#!/bin/bash
for((i=1;i<=10;i  ));
do 
echo $(expr $i * 3   1);
done
代码语言:javascript复制
#!/bin/bash
for i in $(seq 1 10)
do 
echo $(expr $i * 3   1);
done
代码语言:javascript复制
#!/bin/bash
for i in {1..10}
do
echo $(expr $i * 3   1);
done
代码语言:javascript复制
#!/bin/bash
for((integer = 1; integer <= 5; integer  ))
do
    echo "$integer"
done
代码语言:javascript复制
#!/bin/bash
sum=0
for(( i = 1; i <= 100; i = i   2 ))
do
     let "sum  = i"
done
echo "sum=$sum"

字符型

代码语言:javascript复制
#!/bin/bash
for i in `ls`;
do 
echo $i is file name! ;
done
代码语言:javascript复制
#!/bin/bash
for i in $* ;
do
echo $i is input chart! ;
done
代码语言:javascript复制
#!/bin/bash
for i in f1 f2 f3 ;
do
echo $i is appoint ;
done
代码语言:javascript复制
#!/bin/bash
list="rootfs usr data data2"
for i in $list;
do
echo $i is appoint ;
done

路径型

代码语言:javascript复制
#!/bin/bash
for file in /proc/*;
do
echo $file is file path ! ;
done
代码语言:javascript复制
#!/bin/bash
for file in $(ls *.sh)
do
echo $file is file path ! ;
done

awk

代码语言:javascript复制
#!/bin/bash
awk 'BEGIN{for(i=1; i<=10; i  ) print i}'

while

单行

代码语言:javascript复制
 while : ;do  netstat -n | awk '/^tcp/ {  S[$NF]} END {for(a in S) print a,S[a]}'  ; sleep 1; done; 
代码语言:javascript复制
#!/bin/bash
echo "Please input the num "
read num
factorial=1
while [ "$num" -gt 0 ]
do
    let "factorial= factorial*num"
    let "num--"
done
echo "The factorial is $factorial"

代码语言:javascript复制
#!/bin/bash
for (( i = 1; i <=9; i   ))
do
    
    for (( j=1; j <= i; j   ))
    do
        let "temp = i * j"     
        echo -n "$i*$j=$temp  "
     done 
     
     echo ""   #output newline
done
awk

0 人点赞