Shell脚本学习——基础语法阶段二
Posted 行稳方能走远
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Shell脚本学习——基础语法阶段二相关的知识,希望对你有一定的参考价值。
摘自:Shell脚本学习——基础语法阶段二
作者:正弦定理
发布时间:2021-03-16 15:05:25
网址:https://blog.csdn.net/chinesekobe/article/details/114777113
if [ 条件 ]
then
else
fi #一个if结尾不能少了fi
- 1
- 2
- 3
- 4
- 5
Demo:
#!/bin/bash
echo "Please Input you Data"
read data
if [ $data -gt 0 -a $data -lt 100 ]
then
echo "Yes , data in [0-100]"
else
echo "error"
fi
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
二.选择语句 case
case "条件" in
*)
;;
*)
;;
esac
- 1
- 2
- 3
- 4
- 5
- 6
Demo:
条件判断中 通过 管道 | 可以实现多结果判断
#!/bin/bash
echo "请输入数据"
read data
case "$data" in
yes | Y | Yes | YES | YEs) echo "good"
;;
y) echo "nice"
;;
no) echo "fuck"
;;
n) echo "shift"
;;
*) echo "error"
;; # 可省略最后的 ;;
esac # 和 if fi 一样,必备成套的
exit 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
三.循环语句 for 和 while
(1)while循环
结构:
while [条件]
do
# 代码执行段
done
- 1
- 2
- 3
- 4
死循环while为:
while true
do
# 代码执行段
done
- 1
- 2
- 3
- 4
Demo1:
#!/bin/bash
I=0
while [ $I -lt 5 ]
do
I=`expr $I + 1`
echo -n "Please student score: "
read S
case `expr $S / 10` in
10|9)
echo "The Student : A"
;;
6|7|8)
echo "The Student : B"
;;
*)
echo "The Student : C"
;;
esac
echo "I=$I"
done
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
Demo2:
#!/bin/bash
I=0
while true
do
I=`expr $I + 1`
echo -n "Please student score: "
read S
case `expr $S / 10` in
10|9)
echo "The Student : A"
;;
6|7|8)
echo "The Student : B"
;;
*)
echo "The Student : C"
;;
esac
echo "I=$I"
done
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
(2)for循环
结构:
for * in 条件
do
done
- 1
- 2
- 3
for(( *; *;* ))
do
done
- 1
- 2
- 3
Demo:
#!/bin/bash
sum=0
echo "-----------------------------"
for I in `seq 1 10`
do
echo "I=$I"
sum=`expr $I + $sum`
done
echo "sum = $sum"
echo "-----------------------------"
for ((I = 1 ; I <= 10 ; I++))
do
echo "I = $I"
done
echo "-----------------死循环-------------"
for((;;))
do
echo "si le"
sleep 5s
done
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
(3)break 和 continue
break n ( n 表示跳出的层数 )
Demo1:
if [ $# -lt 5 ]
then
exit
fi
echo "---------------------------------"
for I
do
if [ `expr $I % 2` -eq 1 ]
then
echo "I=$I"
else
continue
fi
done
echo "---------------------------------"
for I
do
if [ `expr $I % 2` -eq 1 ]
then
echo "I=$I"
else
break
fi
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
以上是关于Shell脚本学习——基础语法阶段二的主要内容,如果未能解决你的问题,请参考以下文章