shell编程——基本语法
一、判断语句
1、if……then……if语句
1 2 3 4 5 6 7 8 9 10 11 |
#!/bin/bash read -p "请输入y/n:" ym if [ "$ym" == "Y" -o "$ym" == "y" ]; then echo "你输入的是Y" exit 0 elif [ "$ym" == "N" -o "$ym" == "n" ]; then echo "你输入的是N" exit 0 else echo "你输入的不是N或者Y" fi |
note:if附近很多空格,全部用空格隔开
2、case……esac语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#!/bin/bash read -p "请输入(Y/n):" fei case $fei in y) echo '您输入的是y' ;; Y) echo '您输入的是Y' ;; n) echo '您输入的是n' ;; N) echo '您输入的是N' ;; *) echo '您输入的不符合要求' ;; esac |
二、循环语句
1、while语句
1 2 3 4 5 6 7 8 9 |
#!/bin/bash s=0 i=0 while [ "$i" != 100 ] do i=$(($i+1)) s=$(($s+$i)) done echo "the result of '1+2+……+100' is $s" |
2、until语句
1 2 3 4 5 6 |
#!/bin/bash until [ "$yn" == "yes" -o "$yn" == "YES" ] do read -p "Please input yes/YES to stop this program: " yn done echo "OK! you input the correct answer." |
note:当until满足是进入循环,和while相反
3、for…do…done语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#举例一 #!/bin/bash for var in xi fen fei do echo "this is ${var} " done #举例二 #!/bin/bash filelist=$(ls -la) for var in v$filelist do echo "${var}" done #举例三 #!/bin/bash s=0 for i in $(seq 1 100) do s=$(($s+$i)) done echo "the result of '1+2+……+100' is $s" #举例四 #!/bin/bash echo "请输入从1开始累加到N的值:" read nu s=0 for((i=1;i<=$nu;i=i+1)) do s=$(($s+$i)) done echo "1+……+$nu is ==>$s" |
发表评论
要发表评论,您必须先登录。