大家好,我是云计算磊哥,从业20年的IT老鸟。运维培训15年,总结了一套从入门到精通的全运维开发宝典手册。准备用300天时间写一套博文,手把手从安装软件讲起,从linux系统管理,shell脚本编程,mysql运维架构备份核心技术,Apache/nginx/tomcatWEB服务器管理,ansible自动化运维,redis集群哨兵,LVM/HAproxy/keepalived集群架构,rabbitMQ消息队列,docker&K8S集群资源管理,K8S自愈,K8S自动扩容,PYTHON编程,PYTHON自动化运维,从行业到产品,从过去到未来,从理论到操作,从视频到文档工具,100+篇系列文章一站式发布。从零基础入门到30k运维开发工程师岗位诸多就业问题。多方位全方面的给你讲清楚云计算这个行业该如何做。关注我。后续AI大模型开发课程更精彩。


shell阶段介绍

​ 想学 Linux 运维却不知道从哪入手?这套 Shell 脚本实战博文一次性讲透!变量、判断、循环、函数、正则、流编辑器全覆盖,手把手教你写自动化脚本,从脚本创建到全服务器状态巡检脚本输出HTML页面检测,真正做到学完即用,快速提升运维实战能力。

Shell编程初识

1.Shell概览

1.1Shell能做什么?

a.自动化批量系统初始化程序 (update,软件安装,时区设置,安全策略…)

b.自动化批量软件部署程序 (LAMP,LNMP,Tomcat,LVS,Nginx)

c.应用管理程序 (KVM,集群管理扩容,MySQL,DELLR720批量RAID)

d.日志分析处理程序(PV, UV, 200, !200, top 100, grep/awk)

e.自动化备份恢复程序(MySQL完全备份/增量 + Crond)

f.自动化管理程序(批量远程修改密码,软件升级,配置更新)

g.自动化信息采集及监控程序(收集系统/应用状态信息,CPU,Mem,Disk,Net,TCP Status,Apache,MySQL)

h.配合Zabbix信息采集(收集系统/应用状态信息,CPU,Mem,Disk,Net,TCP Status,Apache,MySQL)

i.自动化扩容(增加云主机——>业务上线) zabbix监控CPU 80%+|-50% Python API AWS/EC2(增加/删除云主机) + Shell Script(业务上线)

j.俄罗斯方块,打印三角形,打印圣诞树,打印五角星,运行小火车,坦克大战,排序算法实现

k.Shell可以做任何事(一切取决于业务需求)

1.2程序语言的执行

C —— 编译 —— 二进制机器码 (CPU X86复杂指令集, Power精简指令集, APM)

Java —— 编译 —— 字节码(Java虚拟机 JDK) Tomcat/Hadoop

shell —— 解释 (/usr/bin/bash)

perl —— 解释 (/usr/bin/perl)

expect—— 解释 (/usr/bin/expect)

Python —— 解释 ( /usr/bin/python) —— 编译 —— 字节码(Python虚拟机)

程序是由哪些组程序: 逻辑 + 数据

2.Bash Shell
2.1Shell技术

a.shell特性

b.shell变量

c.shell条件测试

d.shell数值运算

e.流控、循环

if、case、for、while、until、break、continue、exit、shift、array、function

2.2 shell?命令解释器

shell命令 cp ls date

Linux支持的shell

[root@xulei]# cat /etc/shells

[root@xulei]# chsh -l

2.3 GNU/bash shell特点

a.命令和文件自动补齐

b.命令历史记忆功能 上下键、!number、!string、!$、!!、^R

c.别名功能 alias、unalias cp、~username/.bashrc、\cp -rf /etc/hosts .

d.快捷键 R、D、A、E、L、U、K、Y、S、Q

e.前后台作业控制 &、nohup、C、Z、bg %1、fg %1、kill %3、screen

f.输入输出重定向 0,1,2 > >> 2> 2>> 2>&1 &> cat < /etc/hosts cat <file1 <<EOF

实例:

[root@xulei ~]# ll /dev/std*
lrwxrwxrwx 1 root root 15 Sep  1  2026 /dev/stderr -> /proc/self/fd/2
lrwxrwxrwx 1 root root 15 Sep  1  2026 /dev/stdin -> /proc/self/fd/0
lrwxrwxrwx 1 root root 15 Sep  1  2026 /dev/stdout -> /proc/self/fd/1

g. 管道 | tee

[root@xulei ~]# ip addr |grep 'inet ' |grep eth0
[root@xulei ~]#ip addr |grep 'inet ' |tee test |grep eth0覆盖
[root@xulei ~]#ip addr |grep 'inet ' |tee -a test |grep eth0	-a 追加
[root@xulei ~]#df |grep '/$'
[root@xulei ~]#df |tee df.txt |grep '/$'	
[root@xulei ~]# date > date.txt
[root@xulei ~]# date |tee date.txt
Fri Aug 25 15:30:20 CST 2017

h.命令排序

;               不具备逻辑判断
cd; eject	
&&    ||		具备逻辑判断		
[root@xulei ~]#./configure && make && make install	(命令返回值 echo $?)
[root@xulei ~]#mkdir /var/111/222/333 && echo ok
[root@xulei ~]#mkdir -p /var/111/222/333 && echo ok
[root@xulei ~]#ls /home/111/222/333/444 || mkdir -p /home/111/222/333/444
[root@xulei ~]#[ -d /home/111/222/333/444 ] || mkdir -p /home/111/222/333/444
[root@xulei ~]#ping -c1 10.18.42.1 &>/dev/null  && echo up || echo down
注意:
command &							后台执行
command &>/dev/null			混合重定向(标准输出1,错误输出2)
command1 && command2		命令排序,逻辑判断

i.shell通配符(元字符)表示的不是本意

*	匹配任意多个字符  ls in*   rm -rf *  rm -rf *.pdf  find / -iname "*-eth0"
?	匹配任意一个字符  touch love loove live l7ve; ll l?ve
[]	匹配括号中任意一个字符 [abc] [a-z] [0-9] [a-zA-Z0-9] 
()	在子shell中执行(cd /boot;ls)   (umask 077; touch file1000)
{} 集合	touch file{1..9} 
[root@xulei ~]# mkdir /home/{111,222}	
[root@xulei ~]# mkdir -pv /home/{333/{aaa,bbb},444}
[root@xulei ~]# cp -rv /etc/sysconfig/network-scripts/ifcfg-eth0 /etc/sysconfig/network-scripts/ifcfg-eth0.old			
[root@xulei ~]# cp -rv /etc/sysconfig/network-scripts/{ifcfg-eth0,ifcfg-eth0.old}
[root@xulei ~]# cp -rv /etc/sysconfig/network-scripts/ifcfg-eth0{,.old	
\	转义符,让元字符回归本意
[root@xulei ~]# echo *		
[root@xulei ~]# echo \*
[root@xulei ~]# touch xu\ lei		
[root@xulei ~]#mkdir \\
[root@xulei ~]#echo -e "atb"
[root@xulei ~]#echo -e "a\tb"
[root@xulei ~]#echo -e "anb"	
[root@xulei ~]#echo -e "a\nb"			

j.变量

k.shell script 脚本

3.Shell变量
3.1变量的类型
1. 自定义变量
	定义变量:变量名=变量值 变量名必须以字母或下划线开头,区分大小写   ip1=192.168.2.115 
	引用变量:		$变量名 或 ${变量名}
	查看变量:		echo $变量名  set(所有变量:包括自定义变量和环境变量)
	取消变量:		unset 变量名
	作用范围:		仅在当前shell中有效		
2. 环境变量
	定义环境变量:方法一 export back_dir2=/home/backup 
				方法二 export back_dir1 将自定义变量转换成环境变量
	引用环境变量:	$变量名 或 ${变量名}
	查看环境变量:	echo $变量名  env   例如env |grep back_dir2
	取消环境变量:	unset 变量名
	变量作用范围:	在当前shell和子shell有效
3. 位置变量
		$1 $2 $3 $4 $5 $6 $7 $8 $9 ${10}
4. 预定义变量
	    $0  脚本名
		$*	所有的参数
		$@ 	所有的参数
		$# 	参数的个数
		$$ 	当前进程的PID
		$!  上一个后台进程的PID
		$?	上一个命令的返回值 0表示成功

预定义变量和位置示例:

1.[root@xulei ~]# vim test.sh
echo "第2个位置参数是$2"
echo "第1个位置参数是$1"
echo "第4个位置参数是$4"
echo "所有参数是: $*"
echo "所有参数是: $@"
echo "参数的个数是: $#"
echo "当前进程的PID是: $$"
echo '$1='$1
echo '$2='$2
echo '$3='$3
echo '$*='$*
echo '$@='$@
echo '$#='$#
echo '$$='$$	
2.[root@xulei ~]# vim ping.sh
		#!/bin/bash							
		ping -c2 $1 &>/dev/null		        
		if [ $? = 0 ];then					
        		echo "host $1 is ok"	    
		else											
        		echo "host $1 is fail"	    
		fi											
[root@xulei ~]# chmod a+x ping.sh
[root@xulei ~]# ./ping.sh 192.168.2.25	
3.2变量的赋值方式
1. 显式赋值
	变量名=变量值
	示例:
		ip1=192.168.1.251
		school="BeiJing 1000phone"
		today1=`date +%F`
		today2=$(date +%F)			
2. read 从键盘读入变量值
		read 变量名
		read -p "提示信息: "  变量名
		read -t 5 -p "提示信息: "  变量名
		read -n 2 变量名		
示例1:
[root@xulei ~]# vim first.sh
back_dir1=/var/backup
read -p "请输入你的备份目录: " back_dir2
echo $back_dir1
echo $back_dir2
[root@xulei ~]# sh first.sh	
示例2:
[root@xulei ~]# vim ping2.sh
#!/bin/bash							
read -p "Input IP: " ip                
ping -c2 $ip &>/dev/null		
if [ $? = 0 ];then					
   echo "host $ip is ok"	    
else											
   echo "host $ip is fail"	    
fi											
[root@xulei ~]# chmod a+x ping2.sh
[root@xulei ~]# ./ping.sh
3.3定义或引用变量时注意事项
" "  	弱引用
' ' 	    强引用
[root@xulei ~]# school=1000phone
[root@xulei ~]# echo "${school} is good"
		1000phone is good
[root@xulei ~]# echo '${school} is good'
		${school} is good
` `  	命令替换 等价于 $()   反引号中的shell命令会被先执行
[root@xulei ~]# touch `date +%F`_file1.txt  
        [root@blackmed ~]# touch $(date +%F)_file2.txt 
			   
		[root@blackmed ~]# disk_free3="df -Ph |grep '/$' |awk '{print $4}'"	错误
		[root@blackmed ~]# disk_free4=$(df -Ph |grep '/$' |awk '{print $4}')
		[root@blackmed ~]# disk_free5=`df -Ph |grep '/$' |awk '{print $4}'`
3.4变量的运算
1. 整数运算
方法一:
expr
expr 1 + 2
expr $num1 + $num2    			+  -  \*  /  %
方法二 算式置换:
$(())
echo $(($num1+$num2))      		+  -  *  /   %
echo $((num1+num2))
echo $((5-3*2))	 
echo $(((5-3)*2))
echo $((2**3))
sum=$((1+2)); echo $sum
方法三:
$[]
echo $[5+2]						+  -  *  /  %
echo $[5**2]
方法四:
let
let sum=2+3; echo $sum
let i++; echo $i
2. 小数运算
echo "2*4" |bc
echo "2^4" |bc
echo "scale=2;6/4" |bc
awk 'BEGIN{print 1/2}'
echo "print 5.0/2" |python
4.Shell脚本
4.1Shell脚本执行方式
[root@xulei]# ./01.sh	 需要执行权限	      在子shell中执行
[root@xulei]# bash 01.sh	 不需要执行权限	 在子shell中执行
[root@xulei]# . 01.sh	 不需要执行权限	 在当前shell中执行
[root@xulei]# source 01.sh不需要执行权限	 在当前shell中执行
提示:通常修改系统配置文件中如 /etc/profile 的PATH等变量后,使之在当前shell中生效
4.2调试脚本
[root@xulei]# sh -n 02.sh    仅调试 syntax error
[root@xulei]# sh -vx 02.sh	以调试的方式执行,查询整个执行过程

配套视频教材

https://edu.51cto.com/course/39717.html

https://edu.csdn.net/course/detail/40863

Logo

openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构

更多推荐