技术流ken

运维拯救世界

DAY20: 课堂记录-shell编程(三)–技术流ken

if语句

 

1. if单分支

if 条件表达式 ;then

command

fi

 

例子1:

脚本:

#!/bin/bash
if [ 1 -eq 1 ];then
echo “true”
fi

执行:

[root@ken ~]# bash test1.sh
true

 

例子2:

脚本内容:

[root@ken ~]# cat test1.sh
#!/bin/bash
systemctl restart network
if [ $? -eq 0 ];then
echo “重启网卡成功!”
fi

执行结果:
[root@ken ~]# bash test1.sh
重启网卡成功!

 

例子3:

脚本内容:

[root@ken ~]# cat test1.sh
#!/bin/bash
if systemctl restart network;then
echo “重启网卡成功!”
fi

 

脚本执行:
[root@ken ~]# bash test1.sh
重启网卡成功!

 

2. if双分支

if 条件表达式;then

commadn

else

command

fi

 

例子1:

[root@ken ~]# cat test1.sh
#!/bin/bash
if systemctl restart networkii &>/dev/null;then
echo “重启网卡成”
else
echo “由于某些原因网卡重启失败~”
fi
[root@ken ~]# bash test1.sh
由于某些原因网卡重启失败~

 

例子2:

[root@ken ~]# cat test2.sh
#!/bin/bash
num=`ps aux | grep “crond” | grep -v -c “grep”`
if [ $num -eq 1 ];then
echo “计划任务正在运行!”
else
echo “计划任务没有在运行!”
fi

执行结果:

计划任务正在执行:

[root@ken ~]# bash test2.sh
计划任务正在运行!

 

停掉计划任务:

[root@ken ~]# systemctl stop crond
[root@ken ~]# bash test2.sh
计划任务没有在运行!

 

例子3:判断一个主机是否在线

[root@ken ~]# cat test3.sh
#!/bin/bash
ip=$1
if ping -c 1 -w 1 $ip &>/dev/null;then
echo “$ip在线”
else
echo “$ip不在线”
fi

 

执行结果:

主机在线:

[root@ken ~]# bash test3.sh 192.168.64.5
192.168.64.5在线

 

主机不在线:

[root@ken ~]# bash test3.sh 192.168.64.6
192.168.64.6不在线

 

 

3.if多分支

 

if 条件表达式;then

CMD

elif 条件表达式;then

CMD

elif 条件表达式;then

CMD

else

CMD

fi

 

例子1:

[root@ken ~]# cat test4.sh
#!/bin/bash
num=`echo $RANDOM`
if [ $num -lt 1000 ];then
echo “$num小于1000”
elif [ $num -ge 1000 -a $num -lt 2000 ];then
echo “$num大于等于1000,小于2000”
elif [ $num -ge 2000 -a $num -lt 3000 ];then
echo “$num大于等于2000,小于3000”
elif [ $num -ge 3000 -a $num -lt 4000 ];then
echo “$num大于等于3000,小于4000”
else
echo “$num大于等于4000”
fi

 

执行脚本:

[root@ken ~]# bash test4.sh
3518大于等于3000,小于4000
[root@ken ~]# bash test4.sh
5964大于等于4000
[root@ken ~]# bash test4.sh
19047大于等于4000
[root@ken ~]# bash test4.sh
5085大于等于4000
[root@ken ~]# bash test4.sh
9475大于等于4000
[root@ken ~]# bash test4.sh
20827大于等于4000
[root@ken ~]# bash test4.sh

 

 

练习题1:计算器

[root@ken ~]# cat test6.sh
#!/bin/bash
read -p “请输入第一个数字:” num1
read -p “请输入运算符{+|-|*|/}:” num2
read -p “请输入第二个数字:” num3
if [ -n “$num1” -a -n “$num2” -a -n “$num3” ];then
if [ “$num2” == “+” ];then
echo “${num1}${num2}${num3}=$((${num1}${num2}${num3}))”
elif [ “$num2” == “-” ];then
echo “${num1}${num2}${num3}=$((${num1}${num2}${num3}))”
elif [ “$num2” == “*” ];then
echo “${num1}${num2}${num3}=$((${num1}${num2}${num3}))”
elif [ “$num2” == “/” ];then
echo “${num1}${num2}${num3}=$((${num1}${num2}${num3}))”
else
echo “请您输入运算符{+|-|*|/}”
fi
else
echo “您输入的数字或者字符有误!”
fi

 

执行结果:

[root@ken ~]# bash test6.sh
请输入第一个数字:4
请输入运算符{+|-|*|/}:+
请输入第二个数字:4
4+4=8
[root@ken ~]# bash test6.sh
请输入第一个数字:8
请输入运算符{+|-|*|/}:/
请输入第二个数字:0
test6.sh: line 13: 8/0: division by 0 (error token is “0”)
[root@ken ~]# bash test6.sh
请输入第一个数字:8
请输入运算符{+|-|*|/}:/
请输入第二个数字:2
8/2=4

 

练习题2:

[root@ken ~]# cat test7.sh
#!/bin/bash
read -p “请输入一个用户:” user
if id $user &>/dev/null;then
echo “$user存在!”
else
echo “$user不存在!”
fi

 

执行结果:

[root@ken ~]# bash test7.sh
请输入一个用户:root
root存在!
[root@ken ~]# bash test7.sh
请输入一个用户:ken
ken存在!
[root@ken ~]# bash test7.sh
请输入一个用户:kl
kl不存在!

 

for循环

格式:

for i in 取值列表

do

CMD

done

 

例子1:创建100个用户

[root@ken ~]# cat test8.sh
#!/bin/bash
for i in `seq 100`
do
useradd user$i
done

 

执行结果:

[root@ken ~]# bash test8.sh
[root@ken ~]# tail /etc/passwd
user91:x:1091:1091::/home/user91:/bin/bash
user92:x:1092:1092::/home/user92:/bin/bash
user93:x:1093:1093::/home/user93:/bin/bash
user94:x:1094:1094::/home/user94:/bin/bash
user95:x:1095:1095::/home/user95:/bin/bash
user96:x:1096:1096::/home/user96:/bin/bash
user97:x:1097:1097::/home/user97:/bin/bash
user98:x:1098:1098::/home/user98:/bin/bash
user99:x:1099:1099::/home/user99:/bin/bash
user100:x:1100:1100::/home/user100:/bin/bash

 

例子2:创建100个用户并设置6位随机密码

[root@ken ~]# cat test9.sh
#!/bin/bash
for i in `seq 10`
do
useradd user$i
pass=`echo $RANDOM | md5sum | cut -c 1-6`
echo “$pass” | passwd –stdin “user$i”
echo -e “账户:user$i\n密码:$pass”>> /root/passwd
done

 

执行结果:

[root@ken ~]# cat passwd
账户:user1
密码:69a70a
账户:user2
密码:444c02
账户:user3
密码:6b381f
账户:user4
密码:28d8fd

 

例子3:批量检测当前主机在线情况

[root@ken ~]# cat test10.sh
#!/bin/bash
ip=192.168.64.
for i in `seq 10`
do
if ping -c 1 -w 1 $ip$i &>/dev/null;then
echo “$ip$i在线”
sleep 1
else
echo “$ip$i不在线”
sleep 1
fi
done

执行结果:

[root@ken ~]# bash test10.sh
192.168.64.1不在线
192.168.64.2在线
192.168.64.3不在线
192.168.64.4在线
192.168.64.5在线
192.168.64.6不在线
192.168.64.7不在线
192.168.64.8不在线
192.168.64.9不在线
192.168.64.10不在线

 

例子4:批量检测当前主机在线情况,引用/etc/init.d/functions

[root@ken ~]# cat test11.sh
#!/bin/bash
. /etc/init.d/functions
ip=192.168.64.
for i in `seq 10`
do
if ping -c 1 -w 1 $ip$i &>/dev/null;then
echo -n “$ip$i”
success
echo ” ”
sleep 1
else
echo -n “$ip$i”
failure
echo ” ”
sleep 1
fi
done

 

执行结果:

[root@ken ~]# bash test11.sh
192.168.64.1 [FAILED]
192.168.64.2 [ OK ]
192.168.64.3 [FAILED]
192.168.64.4 [ OK ]
192.168.64.5 [ OK ]
192.168.64.6 [FAILED]
192.168.64.7 [FAILED]
192.168.64.8 [FAILED]
192.168.64.9 [FAILED]
192.168.64.10 [FAILED]

 

 

练习题1:计算100以内的奇数和

[root@ken ~]# cat test12.sh
#!/bin/bash
sum=0
for i in `seq 1 2 100`
do
let sum+=$i
done
echo “$sum”

 

执行结果:

[root@ken ~]# bash test12.sh
2500

 

练习题2:计算100以内的偶数和

 

[root@ken ~]# cat test13.sh
#!/bin/bash
sum=0
for i in `seq 2 2 100`
do
let sum+=$i
done
echo “$sum”

 

执行结果:

[root@ken ~]# bash test13.sh
2550

 

练习题3:判断/root目录下面的文件类型

#!/bin/bash
for i in `ls /root`
do
type1=`ls -ld $i | cut -c 1`
if [ “$type1” == “-” ];then
echo “$i是普通文件”
elif [ “$type1” == “l” ];then
echo “$i是连接文件”
elif [ “$type1” == “d” ];then
echo “$i是目录”
else
echo “该文件类型无法识别”
fi
done

 

执行结果:

[root@ken ~]# bash error.sh
error.sh是普通文件
free_mem是普通文件
ken是目录
nohup.out是普通文件
passwd是普通文件
t是普通文件
test10.sh是普通文件
test11.sh是普通文件
test12.sh是普通文件
test13.sh是普通文件
test15.sh是普通文件
test16.sh是普通文件
test18.sh是普通文件
test19.sh是普通文件

 

 

while循环

 

while 条件表达式

do

CMD

done

 

例子1:持续检测内存剩余量,并每隔1分钟输出至一个文件中

[root@ken ~]# cat test15.sh
#!/bin/bash
while true
do
mem=`free -h | grep “Mem” | cut -d “M” -f 4 | tr -d ” “`
echo “$(date “+%F %T”) $mem” >> /root/free_mem
sleep 2
done

 

执行结果:

[root@ken ~]# tail -f free_mem
2019-05-31 11:39:11 736
2019-05-31 11:39:13 736
2019-05-31 11:39:15 736
2019-05-31 11:39:17 736
2019-05-31 11:39:19 736
2019-05-31 11:39:21 736
2019-05-31 11:39:23 736

 

例子2:持续检测内存剩余量,并每隔1分钟输出至一个文件中,并放在后台运行

1.&

[root@ken ~]# bash test15.sh &

这种写法关闭终端之后脚本退出

2. nohup

[root@ken ~]# nohup bash test15.sh &

这种写法终端关闭没有影响

 

关掉脚本:

ps aux

 

[root@ken ~]# ps aux | grep test15
root 7510 0.1 0.1 113176 1440 ? S 11:41 0:00 bash test15.sh
root 7720 0.0 0.0 112704 956 pts/0 R+ 11:42 0:00 grep –color=auto test15
[root@ken ~]# kill -9 7510

 

例子3:逐行读取文件内容

 

第一种写法:

[root@ken ~]# cat test16.sh
#!/bin/bash
cat /etc/passwd | while read line
do
echo “$line”
sleep 1
done

 

执行结果:

[root@ken ~]# bash test16.sh
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin

 

第二种写法:

[root@ken ~]# cat test18.sh
#!/bin/bash
while read line
do
echo “$line”

done < /root/passwd

 

执行结果:

[root@ken ~]# bash test18.sh
账户:user1
密码:69a70a
账户:user2
密码:444c02
账户:user3

 

 

break和continue语句

 

两个语句只能用在循环语句中!

 

break 是终止循环。

continue 是跳出当前循环。

 

例子1:break

[root@ken ~]# cat test19.sh
#!/bin/bash
num=1
while true
do
let num++
if [ $num -eq 5 ];then
break
fi
echo “$num”
done

 

 

执行结果:

[root@ken ~]# bash test19.sh
2
3
4

 

例子2:continue

[root@ken ~]# cat test20.sh
#!/bin/bash
num=0
while true
do
let num++
if [ $num -eq 5 ];then
continue
fi
echo “$num”
done

 

执行结果:

[root@ken ~]# bash test20.sh | head
1
2
3
4
6
7
8
9
10
11

 

 

实际用法:

#!/bin/bash
while true
do
num=`ss -tnl | grep “80” | wc -l`
if [ $num -eq 0 ];then
systemctl restart nginx
if [ $? -ne 0 ];then
echo “`date ‘+%F %T’` 152.136.127.116腾讯云主机web服务宕机,技术流ken请尽快上线修复!” | mail -s “152.136.127.116腾讯云主机 web宕机” 1614833188@qq.com
exit
else
echo “`date ‘+%F %T’` 152.136.127.116腾讯云主机 web宕机已自动恢复” | mail -s “152.136.127.116腾讯云主机 web宕机恢复” 1614833188@qq.com
continue
fi
fi
done

 

case语句

 

例子1:

[root@ken ~]# cat test21.sh
#!/bin/bash
case $1 in
start)
echo “start”;;
stop)
echo “stop”
;;
restart)
echo “restart”;;
*)
echo “Usage: $0 {|start|stop|restart|}”
esac

 

执行结果:

[root@ken ~]# bash test21.sh start
start
[root@ken ~]# bash test21.sh stop
stop
[root@ken ~]# bash test21.sh stopio
Usage: test21.sh {|start|stop|restart|}

9 thoughts on “DAY20: 课堂记录-shell编程(三)–技术流ken

  1. There are actually numerous details like that to take into consideration. That is a nice point to carry up. I supply the ideas above as common inspiration but clearly there are questions just like the one you deliver up where a very powerful thing will be working in trustworthy good faith. I don?t know if greatest practices have emerged round issues like that, however I am certain that your job is clearly recognized as a fair game. Both boys and girls feel the impact of just a moment抯 pleasure, for the rest of their lives.

  2. I happen to be writing to make you know what a amazing discovery our girl went through going through yuor web blog. She realized many details, not to mention how it is like to possess an awesome teaching nature to have many people easily comprehend several very confusing matters. You undoubtedly exceeded our own desires. Many thanks for presenting those beneficial, healthy, revealing and cool tips about this topic to Lizeth.

  3. I would like to express my thanks to you just for rescuing me from this particular trouble. After exploring through the search engines and meeting views which were not pleasant, I believed my life was over. Being alive minus the approaches to the problems you have resolved by way of your entire guide is a serious case, as well as those that could have in a negative way damaged my career if I had not encountered your web site. Your talents and kindness in playing with all things was important. I’m not sure what I would’ve done if I had not come upon such a step like this. It’s possible to at this point relish my future. Thank you very much for this specialized and sensible help. I will not be reluctant to recommend your site to anybody who requires counselling about this subject matter.

  4. I must express my thanks to this writer for bailing me out of this particular predicament. Just after looking through the the net and meeting tricks that were not productive, I believed my life was well over. Living minus the solutions to the issues you’ve solved through your main guideline is a serious case, as well as those that might have badly affected my entire career if I had not come across your web page. Your personal training and kindness in maneuvering all the pieces was priceless. I’m not sure what I would’ve done if I hadn’t encountered such a solution like this. It’s possible to at this time look ahead to my future. Thanks a lot very much for this skilled and results-oriented guide. I will not think twice to propose your site to any individual who wants and needs assistance on this matter.

  5. Thank you a lot for giving everyone remarkably spectacular chance to read in detail from here. It is usually very kind and also full of a lot of fun for me and my office peers to search the blog particularly thrice in one week to learn the latest issues you will have. And definitely, I am usually contented concerning the extraordinary ideas you serve. Selected 2 tips in this post are in truth the best I’ve had.

  6. I simply wanted to appreciate you all over again. I am not sure the things that I might have tried without the advice shared by you relating to such topic. It became an absolute hard circumstance in my position, however , spending time with the very professional mode you solved the issue forced me to leap with gladness. I’m thankful for this assistance and then wish you know what a powerful job that you are doing teaching many others via your web site. Most probably you’ve never come across any of us.

  7. Thanks so much for providing individuals with remarkably marvellous chance to read in detail from this blog. It’s usually very brilliant plus full of a great time for me personally and my office colleagues to search the blog not less than thrice weekly to study the new secrets you will have. Not to mention, I am also actually satisfied considering the terrific techniques served by you. Some 1 tips in this article are in reality the most effective I’ve ever had.

  8. My husband and i got very more than happy Emmanuel could round up his investigation via the ideas he discovered while using the blog. It’s not at all simplistic to simply choose to be offering methods which some people have been trying to sell. So we fully understand we’ve got you to give thanks to for that. The entire explanations you have made, the straightforward web site menu, the relationships you assist to foster – it’s got most spectacular, and it’s aiding our son in addition to us consider that that article is pleasurable, and that’s especially mandatory. Thank you for everything!

  9. I’m writing to make you know what a fine encounter our daughter obtained reading through your webblog. She noticed a lot of pieces, which included what it is like to have a marvelous coaching character to make other folks effortlessly master specified very confusing subject areas. You really did more than our expected results. Thank you for showing the powerful, trustworthy, revealing not to mention easy tips on the topic to Ethel.

发表评论

邮箱地址不会被公开。