1、for循环
for循环一般格式为:
for 变量 in 列表 do command1 command2 ... commandN done
注意:
1、列表可以用命令替代 比如`ls`
2、{1..6} 花括号,中间两点或1 2 3 #中间是空格,不是逗号之类的
3、for((i=11;i<=15;i++)) #双括号,没空格,没int说明
2、while循环
while command do Statement(s) to be executed if command is true done
注意:
1、i=$((i+1)) #表达式,得双括号加$
2、let i++ #自加1可以用let
3、if elif else fi语句
Shell 有三种 if ... else 语句:
- if ... fi 语句;
- if ... else ... fi 语句;
- if ... elif ... else ... fi 语句。
-
if ... elif ... fi 语句可以对多个条件进行判断,语法为:
if [ expression 1 ] then Statement(s) to be executed if expression 1 is true elif [ expression 2 ] then Statement(s) to be executed if expression 2 is true elif [ expression 3 ] then Statement(s) to be executed if expression 3 is true else Statement(s) to be executed if no expression is true fi
注意:
1、read -p "请输入用户名:" userName #保存输入的变量到userName
4、case语句
case语句格式如下:
case 值 in 模式1) command1 command2 command3 ;; 模式2) command1 command2 command3 ;; *) command1 command2 command3 ;; esac
注意:
1、模式1) 半边括号
2、;;模式判断介绍符
3、*)表示其他模式
4、case语句结束标记为反写esac
5、for while语句实例与运行结果
#!/bin/bash echo "for ========" for i in 1 2 3 #中间是空格,不是逗号之类的 do echo "i:$i" done for i in {5..10} #花括号,中间两点 do echo "i:$i" done for((i=11;i<=15;i++)) #双括号,没空格,没int说明 do echo "i:$i" done echo “while ======” i=1 total=0 while((i<=100)) do total=$((total+i)) i=$((i+1)) #表达式,得双括号加$ done echo "total:$total" i=1 total=0 while((i<=100)) do total=$((total+i)) let i++ #自加1可以用let done echo "total:$total"
[app@VM_4_53_centos cfltest]$ ./forwhile.sh for ======== i:1 i:2 i:3 i:5 i:6 i:7 i:8 i:9 i:10 i:11 i:12 i:13 i:14 i:15 “while ======” total:5050 total:5050
6、if elif else fi语句实例与运行结果
#!/bin/bash echo "if语句=======" read -p "请输入用户名:" userName #保存输入的变量到userName if [ $userName = root ] then echo "welcome root..." elif [ $userName = app ] #elif的写法注意啦 then echo "welcome app ..." else echo "please go out..." fi
[app@VM_4_53_centos cfltest]$ ./contorlshell.sh if语句======= 请输入用户名:root welcome root... [app@VM_4_53_centos cfltest]$ ./contorlshell.sh if语句======= 请输入用户名:app welcome app ... [app@VM_4_53_centos cfltest]$ ./contorlshell.sh if语句======= 请输入用户名:you please go out...
7、case语句实例与运行结果
#!/bin/bash echo "case语句==========" case $1 in #case in start) #半边括号 echo "starting ..." ;; stop) echo "stopping ..." ;; restart) echo "restart ..." ;; *) #其他情况用 * 表示 echo "argument error ..." ;; #每个分支结束加两次分号 esac #case 反过来写
[app@VM_4_53_centos cfltest]$ ./caseesac.sh case语句========== argument error ... [app@VM_4_53_centos cfltest]$ ./caseesac.sh start case语句========== starting ... [app@VM_4_53_centos cfltest]$ ./caseesac.sh restart case语句========== restart ... [app@VM_4_53_centos cfltest]$ ./caseesac.sh stop case语句========== stopping ...