linux shell中循环的用法及总结

linux命令 waitig 2858℃ 百度已收录 0评论

在写脚本时不可避免的会用到循环,在此总结一下linux的shell中,有关循环的用法和总结。

bash的循环用法

shell的种类有很多,有bash、expect等,先介绍下bash中循环的用法,直接用例子来说明比较直观些。

  • 1、数组循环,示例:
arr=("a" "b" "c")  
echo "arr is (${arr[@]})"  
echo "item in array:"  
for i in ${arr[@]}  
do  
 echo "$i"  
done

输出:

arr is (a b c)
item in array:
a
b
c

  • 2、入参类循环,示例:
echo "参数,/$*表示脚本输入的所有参数:"  
for i in $* ; do  
echo $i  
done

输出:

参数,$*表示脚本输入的所有参数:
p1
p2
p3

  • 3、文件循环,示例:
echo '处理文件 /proc/sys/net/ipv4/conf/*/accept_redirects:'  
for File in /proc/sys/net/ipv4/conf/*/accept_redirects; do  
echo $File  
done

输出:

处理文件 /proc/sys/net/ipv4/conf/*/accept_redirects:
/proc/sys/net/ipv4/conf/all/accept_redirects
/proc/sys/net/ipv4/conf/default/accept_redirects
/proc/sys/net/ipv4/conf/eth0/accept_redirects
/proc/sys/net/ipv4/conf/lo/accept_redirects
/proc/sys/net/ipv4/conf/vboxnet0/accept_redirects
/proc/sys/net/ipv4/conf/virbr0/accept_redirects

  • 4、循环指定内容,代码:
echo "直接指定循环内容"  
for i in f1 f2 f3 ;do  
echo $i  
done

输出:

直接指定循环内容
f1
f2
f3

  • 5、自增自减类循环,代码:
echo "自增自减类循环:"  
for (( i=0; i<10; i++)); do  
echo $i  
done

输出:

自增自减类 循环:
0
1
2
3
4
5
6
7
8
9

expect循环用法

  • 示例代码:
puts "---1---"
    for {set i 0} {$i < 10} {incr i} {
        puts "I inside first loop: $i"
    }

    puts "---2---"
    for {set i 3} {$i < 2} {incr i} {
        puts "I inside second loop: $i"
    }

    puts "---3---"
    puts "Start"
    set i 0
    while {$i < 10} {
        puts "I inside third loop: $i"
        incr i
        puts "I after incr: $i"
    }

    set i 0
    incr i
    puts "---4---"
    puts "$i"
    # This is equivalent to:
    set i [expr {$i + 1}]    #expect里的加减法
    puts "---5---"
    puts "$i"
  • 输出:

—1—
    I inside first loop: 0
    I inside first loop: 1
    I inside first loop: 2
    I inside first loop: 3
    I inside first loop: 4
    I inside first loop: 5
    I inside first loop: 6
    I inside first loop: 7
    I inside first loop: 8
    I inside first loop: 9
    —2—
    —3—
    Start
    I inside third loop: 0
    I after incr: 1
    I inside third loop: 1
    I after incr: 2
    I inside third loop: 2
    I after incr: 3
    I inside third loop: 3
    I after incr: 4
    I inside third loop: 4
    I after incr: 5
    I inside third loop: 5
    I after incr: 6
    I inside third loop: 6
    I after incr: 7
    I inside third loop: 7
    I after incr: 8
    I inside third loop: 8
    I after incr: 9
    I inside third loop: 9
    I after incr: 10
    —4—
    1
    —5—
    2


本文由【waitig】发表在等英博客
本文固定链接:linux shell中循环的用法及总结
欢迎关注本站官方公众号,每日都有干货分享!
等英博客官方公众号
点赞 (1)分享 (0)