Shell脚本语法与应用(一)
Shell脚本语法与应用(二)
Shell脚本语法与应用(三)
1、算数表达式
常见有4种表达式写法:分别为let C=$A+$B
、C=`expr $A + $B`
、C=$[$A+$B]
与C=$((A+B))
,我们使用第一种let表达式举例说明。
新建一个test04.txt
文本,里面写入3行数据
[root@localhost shell]# cat test04.txt
aaaaaaa
bbbbbb
cccccc
再新建一个test04.sh
脚本,可以统计test04.txt
中文本行数,并且使用let表达式
判断出行数是奇数还是偶数
[root@localhost shell]# cat test04.sh
#!/bin/bash
#统计test04.txt中文本行数,wc统计行数,cut截取行数后面的字符,f1表示取第一个值
line_count=`wc -l test04.txt | cut -d " " -f1`
#判断行数是奇数还是偶数
let rs=line_count%2
[ $rs -eq 0 ] && echo "行数是偶数"
[ $rs -eq 1 ] && echo "行数是奇数"
执行脚本
[root@localhost shell]# bash test04.sh
行数是奇数
2、数值表达式
参数 | 说明 |
---|---|
-eq | 等于则为真 |
-ne | 不等于则为真 |
-gt | 大于则为真 |
-ge | 大于等于则为真 |
-lt | 小于则为真 |
-le | 小于等于则为真 |
3、分支与循环
2.1、if判断
单分支结构
if [ 条件判断 ]
then
//命令
fi
双分支结构
if [ 条件 1 ];then
条件 1 成立执行,指令集 1
else
条件 1 不成执行指令集 2;
fi
多分支结构
if [ 条件 1 ];then
条件 1 成立,执行指令集 1
elif [ 条件 2 ];then
条件 2 成立,执行指令集 2
else
条件都不成立,执行指令集 3
fi
2.2、for循环
语法格式
for 变量 in 列表 ; do
语句
done
举例:新建test05.sh
脚本,并编写一段循环累加的计算求和代码
[root@localhost shell]# cat test05.sh
#!/bin/bash
# 计算从1累加到n的值,n大于等于1
sum=0
# 先判断传入参数是否合法
if [ $# -ne 1 ];then
echo "参数个数不对"
exit 2
else
if [ $1 -le 1 ];then
echo "参数不能小于或等于1"
exit 3
fi
fi
# 变量求和
for i in `seq 1 $1`;do
let sum=sum+i
done
echo "总和为:$sum"
执行脚本
[root@localhost shell]# bash test05.sh 10 20
参数个数不对
[root@localhost shell]# bash test05.sh -10
参数不能小于或等于1
[root@localhost shell]# bash test05.sh 10
总和为:55
2.3、while循环
非死循环:也支持使用break
关键字跳出循环
while 条件;do
语句
[break]
done
死循环:使用while true
或while:
或while [0]
等都是死循环,如下面示例
while true
do
语句
done
2.4、case
语法格式
case $变量名称 in “值 1")
程序段 1
;;
“值 2")
程序段 2
;;
*)
exit 1
;;
esac
举例:新建test06.sh
脚本,根据输入数值,输出对应星期几
[root@localhost shell]# cat test06.sh
#!/bin/bash
read -p "please input a number[1,7]:" num
case $num in
1)
echo "Mon"
;;
2)
echo "Tue"
;;
3)
echo "Wed"
;;
4)
echo "Thu"
;;
5)
echo "Fir"
;;
[6-7])
echo "weekend"
;;
*)
echo "please input [1,7]"
;;
esac
执行脚本
[root@localhost shell]# bash test06.sh
please input a number[1,7]:6
weekend
转载:https://blog.csdn.net/shaixinxin/article/details/106506205
查看评论