您的位置:首页 > 运维架构 > Shell

NO4.Shell脚本学习——Shell条件测试和流程控制

2017-12-27 22:38 591 查看
test命令
用途:测试特定的表达式是否成立,当条件成立时,命令执行后的返回值为0,否则为其他数值
格式:test 表达式 [条件表达式]
常见的测试类型

测试文件状态



字符串比较



整数值比较



逻辑测试



流程判断

if语句



if例子:

#!/bin/bash
#This is first shell program

score=87
if [ $score -lt 60 ];then
echo '60以下'
elif [ $score -ge 60 ] && [ $score -lt 70 ];then
echo '60-70之间'
elif [ $score -ge 70 ] && [ $score -lt 80 ];then
echo '70-80之间'
elif [ $score -ge 80 ] && [ $score -lt 90 ];then
echo '80-90之间'
else
echo '90以上'
fi


case语句



case例子

#!/bin/bash
#test1.sh

case $1 in
start)
echo 'start...'
;;
stop)
echo 'stop...'
;;
restart)
echo 'restart...'
;;
*)
echo 'please input start|stop|restart'
;;
esac


循环控制
while例子

#!/bin/bash
#whiletest.sh

num=3

while [ $num -gt 0 ]
do
echo $num
num=$(($num-1))
sleep 1
done
echo $num

for例子

#!/bin/bash
#fortest.sh

for i in `cat user.txt`
do
echo $i
useradd $i
echo 123|passwd --stdin $i
done

break例子

#!/bin/bash
#fortest2.sh

for((i=0;i<10;i++))
do
if [ $i -eq 5 ];then
break
fi
done

continue例子

#!/bin/bash
#fortest2.sh

for((i=0;i<10;i++))
do
if [ $i -eq 5 ];then
continue
else
echo $i
fi
done

case 例子more

#!/bin/bash
#fortest2.sh

read -p 'please press one key:' key

case $key in
[a-z]|[A-Z])
echo '字母键!'
;;
[0-9])
echo '数字键!'
;;
*)
echo '功能键!'
;;
esac

shift迁移语句



shell编程Tips



自定义函数



#!/bin/bash
#fortest2.sh

function add(){
num=$1
tot=0

for((i=1;i<=$num;i++))
do
tot=$(($tot+$i))
done
echo $tot
}

add 10
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息