shell编程——基本语法

联系:手机/微信(+86 17813235971) QQ(107644445)

标题:shell编程——基本语法

作者:惜分飞©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]

一、判断语句
1、if……then……if语句

#!/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语句

#!/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语句

#!/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语句

#!/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语句

#举例一
#!/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"

发表评论

邮箱地址不会被公开。 必填项已用*标注

5 × 4 =