shell入门之流程控制语句
【摘要】
1.case
脚本:
#!/bin/bash
#a test about case
case $1 in "lenve") echo "input lenve";; "hello") echo "input hello";; [a-zA-Z]) echo "It's a letter";; [0-9]) echo "It's a number";;
es...
1.case
脚本:
#!/bin/bash
#a test about case
case $1 in "lenve") echo "input lenve";; "hello") echo "input hello";; [a-zA-Z]) echo "It's a letter";; [0-9]) echo "It's a number";;
esac
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
执行效果:
2.while
脚本(注意=两端不能有空格):
#!/bin/bash
#a test about while
a=1
while [ $a -lt 10 ]
do
echo "hello world!${a}"
a=`expr $a + 1`
done
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
输出:
3.until循环类似于while循环,不同的是until是判断条件为false时才会执行
#!/bin/bash
#a test about until
a=11
until [ $a -lt 10 ]
do
echo "hello world!${a}"
a=`expr $a + 1`
done
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
这是一个无限死循环,输出从hello world11到hello world无穷大。
4.break与continue
continue脚本
#!/bin/bash
#a test about continue
a=1
while [ $a -lt 10 ]
do
if [ $a -eq 5 ]
then a=`expr $a + 1` continue
else
echo "hello world!${a}"
fi
a=`expr $a + 1`
done
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
结果:
break脚本:
#!/bin/bash
#a test about break
a=1
while [ $a -lt 10 ]
do
if [ $a -eq 5 ]
then a=`expr $a + 1` break
else
echo "hello world!${a}"
fi
a=`expr $a + 1`
done
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
运行结果:
5.shift指令,参数左移,每执行一次,参数序列顺次左移一个位置,$#的位置减1。此指令可用来分别处理每个参数,移出去的参数不可再用。
一个求和的例子:
#!/bin/bash
#a test about shift
if [ $# -le 0 ]
then
echo "there is no parameters"
exit 0
fi
sum=0
while [ $# -gt 0 ]
do
sum=`expr $sum + $1`
shift
done
echo $sum
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
千万注意=两端不能有空格
运行结果:
文章来源: wangsong.blog.csdn.net,作者:_江南一点雨,版权归原作者所有,如需转载,请联系作者。
原文链接:wangsong.blog.csdn.net/article/details/46832577
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)