# 1.1 修改vim
当前用户家目录下 ~/.vimrc
放在/etc/vimrc (红帽系列) /etc/vim/vimrc(ubuntu debian)
追加
“`sh
set ignorecase
autocmd BufNewFile,BufRead *.py,*.cc,*.sh,*.java,*.bash exec “:call SetTitle()”
func SetTitle()
if expand(“%:e”) =~ ‘sh\|bash’
call setline(1, “#!/bin/bash”)
call setline(2, “##############################################################”)
call setline(3, “# File Name: ” . expand(“%”))
call setline(4, “# Version: V1.0”)
call setline(5, “# Author: ysl”)
call setline(6, “# Organization: www.ysledu.com”)
call setline(7, “# Date: ” . strftime(“%Y-%m-%d %H:%M:%S”))
call setline(8, “# Desc:”)
call setline(9, “##############################################################”)
endif
endfunc
“`
将脚本放入/etc/profile.d/目录下就是登录时显示
### 10.2 特殊变量-位置变量
位置的特殊变量 含义 应用场景
$n 脚本的第n个参数 命令行与脚本的内部桥梁
$0 脚本名字 用于错误提示输出帮助
$# 脚本参数的个数 一般与判断结合,检查脚本个数
$@ $* 取出脚本所有参数 数组或循环
-eq 等于
-ne 不等于
-lt 小于
-le 小于等于
-gt 大于
-ge 大于等于
### 10.3 案例2、检查用户是否存在
#!/bin/bash
#1.vars
user=$1
#2.判断参数个数是否为1,不是1就退出
if [ $# -ne 1 ]
then
echo “help :$0 用户名”
exit
fi
#3.判断用户是否存在
id $user >/dev/null 2>&1
if [ $? -eq 0 ]
then
echo “${user}存在”
else
echo “${user}不存在”
fi
[root@kylin shell]# sh user.sh test
test存在
[root@kylin shell]# sh user.sh mysql
mysql不存在
### 10.4 案例03-检查ip或域名是否可以访问的脚本
[root@kylin shell]# cat 03.check_ping.sh
#!/bin/bash
#1.vars
ip=$1
#2.检查参数个数是否为1,不是则退出
if [ $# -ne 1 ];then
echo “$0 ip或域名”
exit 1
fi
#3.检查输出
ping -c3 -w3 ${ip} > /dev/null 2>&1
if [ $? -eq 0 ];then
echo “${ip}可以ping通”
else
echo “${ip}不通”
fi
[root@kylin shell]# sh 03.check_ping.sh jd.com
jd.com可以ping通
案例04-$n n大于9会有什么问题?
$1…$9 ${10}
以后读取变量数据的时候都使用{}来括起来就不会有这个问题
案例05-通过$# 来完善02-03增加判断
if [ $# -ne 1 ];then
echo “使用说明:sh $0 username”
exit 1
fi
### 10.5 案例06-执行脚本输入1个或多个用户名,通过脚本进行输出
[root@kylin shell]# cat 06.check_multi_users.sh
#!/bin/bash
#1.vars
names=”$@”
#2.检查如果参数为0则退出
if [ $# -eq 0 ];then
echo “用法 bash $0 user1 user2 user3 user4”
exit 1
fi
#.for循环
for name in ${names}
do
id ${name} > /dev/null 2>&1
if [ $? -eq 0 ];then
id ${name}
else
echo “${name}” 不存在
fi
done
[root@kylin shell]# sh 06.check_multi_users.sh test ysl
用户id=1111(test) 组id=1111(test) 组=1111(test),1112(ceshi)
ysl 不存在
[root@kylin shell]# sh 06.check_multi_users.sh
用法 bash 06.check_multi_users.sh user1 user2 user3 user4
[root@kylin shell]#
### 10.6 for循环格式
for 变量 in 变量取值列表
do
命令,if等
done
状态的特殊符号 含义 应用场景
$? 上一个命令、脚本的返回值 一般与判断检查命令结果
\$$ 当前脚本的pid 一般写在脚本中获取脚本id
$! 上一个脚本的pid
$_ 取前一个命令的参数esc+点.
案例09-windows下书写的脚本复制到linux执行异常
现象:windows下书写的脚本,上传到Linux执行报错.
原因:windows下面的回车换行\r\n ,linux下面回车换行\n
解决:替换结束标记即可.dos2unix windows–>linux
或者进脚本set ff=unix
案例10:-通过脚本传参方式输入任何一个命令并执行,检查这个命令执行结果是否正确
[root@kylin shell]# cat 10.check_cmd.sh
#!/bin/bash
#1.检查是否为root
if [ $UID -ne 0 ];then
echo “请使用root用户运行”
exit 1
fi
#2.检查参数个数是否为0
if [ $# -eq 0 ];then
echo “Usage:$0 命令”
exit 2
fi
#3.执行
$* > /dev/null 2>&1
#4.检查
if [ $? -eq 0 ];then
echo “$* 运行成功”
else
echo “$* 运行失败”
fi
[root@kylin shell]# sh 10.check_cmd.sh cat 10.check_cmd.sh
cat 10.check_cmd.sh 运行成功
[root@kylin shell]#
### 10.7 特殊变量-变量子串
变量子串 parameter expension 变量扩展
格式${变量},写为$变量形式无法识别
作用:用于对变量处理加工()
应用:可以不用,如果使用效率高
变量子串parameter为变量名 含义
${parameter} $para 变量取值
${#parameter} 统计字符长度
${parameter#word} 从变量左边开始删除,按最短匹配删除
${parameter##word} 从变量左边开始删除,按最长开始匹配删除
${parameter%word} 从变量右边开始删除,按最短匹配删除
${parameter%%word} 从变量右边开始删除,按最长匹配删除
${var:5} 从下标是5字符开始向后截取字符
${var:5:2} 从下标是5字符开始向后截取2个字符
${para/word/replace} 把word替换为replace,仅替换第一个
${para//word/replace} 把所有word替换为replace
#### 1 统计字符长度
[root@kylin shell]# echo ${#ysl}
8
[root@kylin shell]# echo ${#LANG}
11
[root@kylin shell]# echo ${LANG}
zh_CN.UTF-8
[root@kylin shell]# ysl=”forest”
[root@kylin shell]# echo ${#ysl}
9
统计的时候空格也算一个字符
#### 2 删除变量中的内容(仅影响输出)
[root@kylin shell]# var=”yslforest”
[root@kylin shell]# echo ${var#ysl}
forest
[root@kylin shell]# echo ${var#o}
yslforest
[root@kylin shell]# echo ${var#l}
yslforest
[root@kylin shell]# echo ${var#l}
yslforest
[root@kylin shell]# echo ${var#*l}
dboyforest
[root@kylin shell]# echo ${var#*o}
yslforest
[root@kylin shell]# echo ${var##o}
forest
[root@kylin shell]# echo ${var##*o}
为什么要加*号
[root@kylin shell]# dir=/etc/sysconfig/network-scripts/ifcfg-ens33
[root@kylin shell]# echo ${dir##*/}
ifcfg-ens33
[root@kylin shell]# echo ${dir%/*}
/etc/sysconfig/network-scripts
#### 3 截取(切片)
[root@kylin shell]# var=ysl
[root@kylin shell]# echo ${var}
ysl
[root@kylin shell]# echo ${var:3}
boy
[root@kylin shell]# echo ${var:3:2}
bo
[root@kylin shell]# echo ${var}|cut -c1-3
old
cut也可以取字符串
#### 4 替换
[root@kylin shell]# var=yslforest
[root@kylin shell]# echo ${var/o/-}
-rest
[root@kylin shell]# echo ${var//o/-}
-ldb-ylida-996
[root@kylin shell]#
#### 5 案例 I am ysl teacher welcome to ysl training class
for循环打印上面这句话中字母数不大于6的单词
[root@kylin shell]# cat 09.calc_strings.sh
#!/bin/bash
#1.vars
str=” I am ysl teacher welcome to ysl training class”
num=6
#2.特殊符号替换成空格
str_space=`echo $str | sed ‘s#[,.]# #g’`
#4.for循环
for s in ${str_space}
do
if [ ${#s} -le ${num} ];then
echo “$s单词数小于6”
fi
done
[root@kylin shell]# sh 09.calc_strings.sh
I单词数小于6
am单词数小于6
ysl单词数小于6
to单词数小于6
ysl单词数小于6
class单词数小于6
awk书写
[root@kylin shell]# echo “I am ysl teacher welcome to ysl training class.” | awk -vRS=” ” ‘length()<=6'
I
am
ysl
to
ysl
#### 6 变量子串-小结
掌握计算变量字符串长度,替换
### 10.8 变量赋值
向变量中写入内容
赋值方式 格式
直接赋值 ysl=forest
命令结果赋值 hostname=`hostname`
脚本传参
read交互方式赋值 通过read命令实现
读取文件内容赋值给变量 循环中使用
read通过交互式方式进行赋值
-p 交互的时候提示信息
-t 超时
-s 不显示用户的输入,记录密码时使用
read -t 40 -s -p "请输入密码:" pass
pass是变量
### 10.9 运算符
| shell运算符 | 含义 |
| -------------- | ------------------------------------ |
| +-*/ | 加减乘除 |
| % | 取余 |
| ^或** | 幂、指数 |
| i=i+1或i++ | 计数 |
| j=j+?? j+=? | 求和,累加 |
| && | 前一个命令执行成功,再执行后面的命令 |
| \|\| | 前一个命令执行失败,再执行后面的命令 |
### 10.10 对随机数取余
echo $RANDOM%5 | bc
### 10.11 运算方法
| 运算的命令 | 说明 | 应用场景 |
| ---------- | ------------------------------------------------- | ------------------------------ |
| awk | 可以进行计算,带小数,可以与shell脚本进行变量传递 | 一般计算都可以用awk |
| bc | 带小数 | 一般计算都可以使用bc,需要安装 |
| expr | 计算,整数 | 判断是否为数字 |
| let | 进行计算,整数,变量直接使用即可 | 用于计算i++ |
| $(()) | 进行计算,整数,变量直接使用即可 | |
| $[] | 进行计算,整数,变量直接使用即可 | |
#### 1 awk计算
```sh
root@ubt:~# awk 'BEGIN{print 1/3}'
0.333333
root@ubt:~# awk 'BEGIN{print 1/4*100}'
25
root@ubt:~# awk 'BEGIN{print 1/4*100 + 1/5*100}'
45
root@ubt:~# awk 'BEGIN{print 1/4*100 + 1+5*100}'
526
root@ubt:~# awk 'BEGIN{print 1/4*100 + (1+5)*100}'
625
root@ubt:~# awk -vn1=1 -vn2=3 'BEGIN{print n1/n2}'
0.333333
```
awk -v选项用于创建或修改awk中的变量,-v是shell脚本与awk桥梁
在awk中各种变量直接使用即可,如果加上$n1,会被awk识别为取列
#### 2 案例13:计算器,传入脚本中2个参数,进行计算,输出结果
```sh
root@ubt:/ysl/shell# sh 13.num_calc_parameter.sh 10 20
10 是数字
20 是数字
10 + 20 结果是 30
10 - 20 结果是 -10
10 * 20 结果是 200
10 / 20 结果是 0.5
root@ubt:/ysl/shell# cat 13.num_calc_parameter.sh
#!/bin/bash
##############################################################
# File Name: 13.num_calc_parameter.sh
# Version: V1.0
# Author: ysl
# Organization: www.ysledu.com
# Date: 2024-10-16 12:56:11
# Desc:
##############################################################
#1、vars
num1=$1
num2=$2
#2、判断是否为数字
if echo $num1 | grep -qE '^[0-9]+$';then
echo "$num1 是数字"
else
echo "$num1 不是数字,请输入数字"
fi
if echo $num2 | grep -qE '^[0-9]+$';then
echo "$num2 是数字"
else
echo "$num2 不是数字,请输入数字"
fi
#3、计算
jia=`awk -vn1=$num1 -vn2=$num2 BEGIN'{print n1+n2}'`
jian=`awk -vn1=$num1 -vn2=$num2 BEGIN'{print n1-n2}'`
cheng=`awk -vn1=$num1 -vn2=$num2 BEGIN'{print n1*n2}'`
chu=`awk -vn1=$num1 -vn2=$num2 BEGIN'{print n1/n2}'`
#4、结果
echo $num1 + $num2 结果是 $jia
echo $num1 - $num2 结果是 $jian
echo $num1 \* $num2 结果是 $cheng
echo $num1 / $num2 结果是 $chu
```
#### 3 案例14:计算器,传入脚本中2个参数,进行计算,输出结果。(read)
```sh
root@ubt:/ysl/shell# cat 14.num_calc_parameter.sh
#!/bin/bash
##############################################################
# File Name: 14.num_calc_parameter.sh
# Version: V1.0
# Author: ysl
# Organization: www.ysledu.com
# Date: 2024-10-16 17:05:20
# Desc:
##############################################################
#1/vars
read -p "输入两个数字:" num1 num2
#2、判断是否为数字
if echo $num1 | grep -qE ^[0-9]+$;then
echo "$num1 是数字"
else
echo "${num1} 不是数字"
fi
if echo $num1 | grep -qE ^[0-9]+$;then
echo "$num1 是数字"
else
echo "${num1} 不是数字"
fi
#3/计算
jia=`awk -vn1=$num1 -vn2=$num2 BEGIN'{print n1+n2}'`
jian=`awk -vn1=$num1 -vn2=$num2 BEGIN'{print n1-n2}'`
cheng=`awk -vn1=$num1 -vn2=$num2 BEGIN'{print n1*n2}'`
chu=`awk -vn1=$num1 -vn2=$num2 BEGIN'{print n1/n2}'`
#4/结果
echo "$num1 + $num2 结果是$jia"
echo "$num1 - $num2 结果是$jian"
echo "$num1 \* $num2 结果是$cheng"
echo "$num1 / $num2 结果是$chu"
root@ubt:/ysl/shell# sh 14.num_calc_parameter.sh
输入两个数字:10 20
10 是数字
10 是数字
10 + 20 结果是30
10 - 20 结果是-10
10 \* 20 结果是200
10 / 20 结果是0.5
root@ubt:/ysl/shell#
```
#### 4 bc
-l 显示小数
```sh
root@ubt:/ysl/shell# echo 1/3
1/3
root@ubt:/ysl/shell# echo 1/3 |bc -l
.33333333333333333333
root@ubt:/ysl/shell# echo 1/3 | bc
0
root@ubt:/ysl/shell# echo 2^10
2^10
root@ubt:/ysl/shell# echo 2^10 | bc
1024
root@ubt:/ysl/shell# echo 2^10 | bc -l
1024
root@ubt:/ysl/shell#
```
#### 5 expr
使用注意事项:使用空格,对*号转义
小坑:了解:计算0 + 0 查看命令的返回值。
expr 进行计算的时候结果为0 ,返回值就是1.
可以判断返回值大于1即可.或者等于2也行.
```sh
root@ubt:/ysl/shell# expr 1 + 1
2
root@ubt:/ysl/shell# expr 1 * 1
expr: syntax error: unexpected argument ‘01.show-v3.sh’
root@ubt:/ysl/shell# expr 1 \* 1
1
root@ubt:/ysl/shell# expr 1 - 1
0
root@ubt:/ysl/shell# $?
1: command not found
root@ubt:/ysl/shell# echo $?
127
root@ubt:/ysl/shell# expr 1 - 1
0
root@ubt:/ysl/shell# echo $?
1
root@ubt:/ysl/shell#
```
#### 6 判断是否为数字
1、正则
if echo $num1 | grep -qE ^[0-9]+$;then
echo "$num1 是数字"
else
echo "${num1} 不是数字"
fi
2、expr
expr $num1 + $num2 > /dev/null 2>&1
if [ $? -ge 2 ];then
echo “Usage $0 num1 num2”
exit 1
fi
#### 7 let,$(()),$[]
let
“`sh
root@ubt:/ysl/shell# n1=666
root@ubt:/ysl/shell# n2=999
root@ubt:/ysl/shell# let c=n1+n2
root@ubt:/ysl/shell# echo $c
1665
root@ubt:/ysl/shell# let i++
root@ubt:/ysl/shell#
“`
$(())
“`sh
root@ubt:/ysl/shell# n1=666
root@ubt:/ysl/shell# n2=999
root@ubt:/ysl/shell# echo $((n1+n2))
1665
root@ubt:/ysl/shell# d=$((n1+n2))
root@ubt:/ysl/shell# echo $d
1665
root@ubt:/ysl/shell#
“`
echo $((RANDOM%100)) 生成0-99随机数
$[]
“`sh
root@ubt:/ysl/shell# n1=666
root@ubt:/ysl/shell# n2=999
root@ubt:/ysl/shell# e=$[n1+n2]
root@ubt:/ysl/shell# echo $e
1665
root@ubt:/ysl/shell#
“`
从新写案例01-案例15
根据案例描述(步骤)一步一步写出脚本.
习题: https://www.yuque.com/forest/sre/noqb9gbc71ts5smy
https://www.yuque.com/forest/sre/fh30i4e2qo6l7zsu?singleDoc#
《【Shell阶段】老男孩教育-Shell自动化初级编程-学完shell后》
脚本分析https://www.yuque.com/forest/sre/izry49dqbvomb0iy?singleDo
c# 《老男孩教育-Shell脚本分析案例》
https://www.yuque.com/forest/sre/noqb9gbc71ts5smy)
### 10.12 条件表达式
条件表达式也可以叫条件测试语句
#### 1 案例16-[]和[[]]区别
| 含义与特点 | test或[] | [[]]或(()) |
| ———- | ——————— | ————– |
| 共同点 | 都可以用于判断 | 都可以用于判断 |
| 区别一 | 不支持正则 | 支持正则 |
| 区别二 | 表示与或非-a -o ! -gt | && \|\| ! > |
| 应用场景 | 大部分情况下 | 使用正则时 |
#### 2 条件表达式符号
| 条件表达式符号 | 说明 |
| ————– | ——————– |
| -f | 文件是否存在 |
| -d | 目录是否存在 |
| -x | 是否可执行 |
| -s | 是否大于0 ,非空为真 |
| -r | 是否可读 |
| -w | 是否可写 |
| -nt | 文件修改时间是否更新 |
| -ot | 文件修改时间是否更老 |
| -L或-h | 软连接 |
| -e | 是否存在,任何类型 |
“`sh
root@ubt:/ysl/shell# [ -f /etc/hosts ] && echo “成立 ” || echo “失败”
成立
root@ubt:/ysl/shell# [ -d /etc/ ] && echo “成立 ” || echo “失败”
成立
root@ubt:/ysl/shell# [ -d /etc/hosts ] && echo “成立 ” || echo “失败”
失败
root@ubt:/ysl/shell#
“`
&& 表示前面命令执行成功然后执行echo 成立。
|| 表示前面命令执行失败了,echo 失败
if [ ! -x /sbin/ip ];then
echo “no执行权限”
exit 1
fi
[ -s /etc/hosts ] && echo “成立 ” || echo “失败”
#### 3 案例17-通过脚本传参方式传输一个参数,判断是否为文件,是否为目录,是否具有执行权限
“`sh
root@ubt:/ysl/shell# sh 17.check_file.sh /etc/hosts
17.check_file.sh: 15: [: missing ]
/etc/hosts 是一个文件
/etc/hosts 不是目录
/etc/hosts 没有执行权限
/etc/hosts 不是软连接
root@ubt:/ysl/shell# cat 17.check_file.sh
#!/bin/bash
##############################################################
# File Name: 17.check_file.sh
# Version: V1.0
# Author: ysl
# Organization: www.ysledu.com
# Date: 2024-10-16 18:28:03
# Desc:
##############################################################
#1/vars
file=$1
#2/参数是否是1
if [ $# -eq 0];then
echo “Usage $0 文件名”
exit 1
fi
#3/判断
[ -f $file ] && echo “$file 是一个文件” || echo “$file 不是文件”
[ -d $file ] && echo “$file 是一个目录” || echo “$file 不是目录”
[ -x $file ] && echo “$file 有执行权限” || echo “$file 没有执行权限”
[ -h $file ] && echo “$file 是一个软连接” || echo “$file 不是软连接”
root@ubt:/ysl/shell#
“`
#### 4 字符串对比
用于对比或比较2个字符串内容。
字符串对比的时候加上引号
| 字符串对比 | 说明 |
| —————- | —————— |
| “str1” = “str2” | str1等于str2为真 |
| “str1” != “str2” | str1不等于str2为真 |
| -z “str” | 空为真 |
| -n “str” | 非空为真 |
#### 5 对比两个字符串是否相等
“`sh
root@ubt:/ysl/shell# input=start
root@ubt:/ysl/shell# [ “$input” = “start” ] && echo “成立” || echo “失败”
成立
root@ubt:/ysl/shell# [ “$input” = “start” ] && echo “成立” || echo “失败”
成立
root@ubt:/ysl/shell# str1=forest
root@ubt:/ysl/shell# str2=ysl007
root@ubt:/ysl/shell# [ “str1” = “str2” ] && echo “成立” || echo “失败”
失败
root@ubt:/ysl/shell#
“`
#### 6 在进行字符串比较的时候变量尾巴可以加上个x,防止变量为空,造成匹配/执行失败
“`sh
[root@ysl-devops-shell ~]# [ “${str1}x” = “${str2}x” ] && echo “成立 ” || echo “失败”
失败
[root@ysl-devops-shell ~]# [ “$str1″x = “$str2″x ] && echo “成立 ” || echo “失败”
失败
“`
案例18-检查selinux是否关闭脚本,如果没有关闭,提示是否要关闭,yes则关闭,其他就不关闭
检查selinux是否关闭
检查firewalld是否关闭
“`sh
#1/检查firewalld
active=`systemctl is-active firewalld`
enable=`systemctl is-enabled firewalld`
service=firewalld
if [ “$active” = “active” ];then
echo “$service 已关闭”
else
echo “$service 正在运行中”
fi
if [ “$enable” = “enable” ];then
echo “$service 会开机启动”
else
echo “$service 不会开机启动”
fi
#2/检查selinux
active1=`getenforce`
if [[ $active1 = Disabled ]]; then
echo “selinux 已经关闭”
else
echo “selinux 未关闭” #statements
fi
“`
#### 7 关闭selinux
“`sh
[root@kylin shell]# cat 18.check_stop_selinux.sh
#!/bin/bash
##############################################################
# File Name: 18.check_stop_selinux.sh
# Version: V1.0
# Author: ysl
# Organization: www.ysledu.com
# Date: 2024-10-17 11:16:02
# Desc:
##############################################################
#1/vars
selinux_config=`awk -F= ‘/^SELINUX=/{print $2}’ /etc/selinux/config`
selinux_cmd=`getenforce`
#2/判断是否关闭
if [ “$selinux_config” = “disabled” -a “$selinux_cmd” = “Disabled” ];then
echo “selinux 已经关闭”
else
read -p “是否关闭selinux,请输入yes/no:” xuan
if [ “$xuan” = “yes” ];then
sed -i ‘s/SELINUX=enforcing/SELINUX=disabled/g’ /etc/selinux/config
setenforce 0
else
echo “警告selinux未关闭”
fi
fi
[root@kylin shell]# sh 18.check_stop_selinux.sh
是否关闭selinux,请输入yes/no:yes
setenforce: SELinux is disabled
“`
#### 8 案例19-给使用read指令的脚本增加判断功能,如果变量为空则退出
“`sh
[root@kylin shell]# cat 19.read_shuru.sh
#!/bin/bash
##############################################################
# File Name: 19.read_shuru.sh
# Version: V1.0
# Author: ysl
# Organization: www.ysledu.com
# Date: 2024-10-17 11:30:40
# Desc:
##############################################################
#1/vars
read -p “请输入数字num1 num2:” num1 num2
#2/判断
if [ -z “$num1” ];then
echo “error”
exit 1
fi
if [ -z “$num2” ];then
echo “error”
exit 2
fi
[root@kylin shell]# sh 19.read_shuru.sh
请输入数字num1 num2:
error
[root@kylin shell]# sh 19.read_shuru.sh
请输入数字num1 num2:1 2
“`
#### 9 整数比大小
| 条件表达式-整数相关 | [] | [[]] |
| —————————- | —- | —- |
| 大于 | -gt | > |
| 大于等于 | -ge | >= |
| 小于 | -lt | < |
| 小于等于 | -le | <= |
| 等于 | -eq | == |
| 不等于 | -ne | != |
| 不支持小数的对比,仅支持整数 | | |
比较大小[]
[ 666 -gt 1 ] && echo "成立 " || echo "失败"
成立
[ 0 -gt -1 ] && echo "成立 " || echo "失败"
成立
[ 0 -gt -1000 ] && echo "成立 " || echo "失败"
成立
[ 0 -gt 0.5 ] && echo "成立 " || echo "失败"
-bash: [: 0.5: 期待整数表达式
失败
比较大小[[]]
[[ 60 > 6 ]] && echo “成立 ” || echo “失败”
成立
[[ 6 >= 6 ]] && echo “成立 ” || echo “失败”
-bash: 条件表达式中有语法错误
-bash: `6′ 附近有语法错误
不推荐使用,对比的时候会有语法问题。
这里面也可以用-gt -lt ……..
#### 10 逻辑判断
多个条件表示同时成立,表示或者,表示取反
与或非
| 条件表达式-逻辑判断 | [] | [[]] |
| ——————- | —- | —- |
| 与 | -a | && |
| 或 | -o | \|\| |
| 非 | ! | ! |
与
同时成立
或
前面失败则运行下一个命令
#### 11 使用正则判断
“`sh
[root@kylin shell]# num=666
[root@kylin shell]# [[ $num =~ [0-9]+ ]] && echo 成立 || echo 不成立
成立
[root@kylin shell]# num=forest
[root@kylin shell]# [[ $num =~ [0-9]+ ]] && echo 成立 || echo 不成立
成立
使用正则精确匹配
[root@kylin shell]# [[ $num =~ ^[0-9]+$ ]] && echo 成立 || echo 不成立
不成立
[root@kylin shell]#
“`
#### 12 案例21-书写一个脚本通过read读取输入,判断输入时整数,浮点还是字符
整数正则: ^-?[0-9]+$
浮点数: ^-?[0-9]+.[0-9]+$ 1.0 2.0 3.0 4.5
字符串: ^[a-zA-Z0-9]+$ forest 996ysl li007dao
“`sh
[root@kylin shell]# sh 21.check_type.sh
请输入内容:888
888 是整数
[root@kylin shell]# sh 21.check_type.sh
请输入内容:1.2
1.2 是小数
[root@kylin shell]# sh 21.check_type.sh
请输入内容:00y
00y 是字符串
[root@kylin shell]# cat 21.check_type.sh
#!/bin/bash
##############################################################
# File Name: 21.check_type.sh
# Version: V1.0
# Author: ysl
# Organization: www.ysledu.com
# Date: 2024-10-17 12:20:34
# Desc:
##############################################################
#1/vars
read -p ‘请输入内容:’ str
#2、检查str是否为空
if [ -z $str ];then
echo “请输入内容”
exit 5
fi
if [[ “$str” =~ ^-?[0-9]+$ ]];then
echo “$str 是整数”
exit 1
fi
if [[ “$str” =~ ^-?[0-9]+\.[0-9]+$ ]];then
echo “$str 是小数”
exit 2
fi
if [[ “$str” =~ ^[a-zA-Z0-9]+$ ]];then
echo “$str 是字符串”
exit 3
fi
[root@kylin shell]#
“`
#### 13 条件表达式小结
| 条件表达式分类 | 必会 | 熟悉 |
| ————– | ———————– | ——————- |
| 文件 | -f -d -x -s | -r -w -nt -ot -L… |
| 字符串比较 | = != == | -n -z |
| 比较大小 | -eq -ne -gt -ge -lt -le | |
| 逻辑 | -a -o ! | |
| 正正则 | | |
if
#### 14 单分支判断
if 条件;then
满足条件后执行的内容
fi
“`sh
[ $# -eq 2 ] || {
echo “必须要2个数字”
exit 1
}
if [ $# -ne 2 ];then
echo “脚本必须要2个参数”
exit 1
fi
“`
#### 15 双分支判断
“`sh
if 条件;then
满足条件后执行的内容。
else
不满足条件执行的内容。
fi
if 丁同学条件;then
迎娶白富美,富婆.
else
是个女的就行.
fi
“`
#### 16 案例22-书写服务检查脚本,执行的时候输入服务名字检查是否运行,检查是否开机自启
“`sh
[root@kylin shell]# sh 22.check_service.sh sshd
sshd 已开机启动
sshd 未启动
[root@kylin shell]# systemctl is-active sshd
active
[root@kylin shell]# vim 22.check_service.sh
[root@kylin shell]# sh 22.check_service.sh sshd
sshd 已开机启动
sshd 正在运行中
[root@kylin shell]# sh 22.check_service.sh firewalld
firewalld 未开机启动
firewalld 未启动
[root@kylin shell]# cat 22.check_service.sh
#!/bin/bash
##############################################################
# File Name: 22.check_service.sh
# Version: V1.0
# Author: ysl
# Organization: www.ysledu.com
# Date: 2024-10-17 12:58:29
# Desc:
##############################################################
#1.vars
service_names=$1
#2.检查是否为空
if [ -z $service_names ];then
echo “Usage $0 服务名”
exit 1
fi
#3.检查服务是否存在
ser_cnt=`systemctl list-unit-files | grep $service_names | wc -l`
if [ $ser_cnt -eq 0 ];then
echo “$service_names 服务不存在,请安装服务”
exit 2
fi
#4.检查服务是否开机启动
kjqd=`systemctl is-enabled $service_names`
if [ “$kjqd” = “enabled” ];then
echo “$service_names 已开机启动”
else
echo “$service_names 未开机启动”
fi
#5.检查是否启动
qd=`systemctl is-active $service_names`
if [ “$qd” = “active” ];then
echo “$service_names 正在运行中”
else
echo “$service_names 未启动”
fi
“`
#### 17 多分支判断
“`sh
#第1次判断
if 条件;then
满足条件后执行的内容。
#第2次判断
elif 条件;then #else if
满足elif条件,执行的内容。
#第3次判断 还可以继续增加.
elif 条件;then
满足elif条件,执行的内容。
else
不满足条件执行的内容。
fi
“`
#### 18 案例23-书写多分支格式比较大小的脚本
“`sh
[root@kylin shell]# sh 23.compare_num.sh 1 2
1 小于 2
[root@kylin shell]# sh 23.compare_num.sh 2 1
2 大于 1
[root@kylin shell]# sh 23.compare_num.sh 1 1
1 等于1
[root@kylin shell]# cat 23.compare_num.sh
#!/bin/bash
##############################################################
# File Name: 23.compare_num.sh
# Version: V1.0
# Author: ysl
# Organization: www.ysledu.com
# Date: 2024-10-17 16:43:16
# Desc:
##############################################################
#1.vars
num1=$1
num2=$2
#2.判断参数是否为2
if [ $# -ne 2 ];then
echo “Usage:$0 数字1 数字2”
exit 1
fi
#3.判断是否为数字
if [[ ! $num1 =~ ^-?[0-9]+$ ]];then
echo “请输入数字”
exit 2
fi
if [[ ! $num2 =~ ^-?[0-9]+$ ]];then
echo “请输入数字”
exit 2
fi
#4.判断大小
if [ $num1 -gt $num2 ];then
echo “$num1 大于 $num2”
elif [ $num1 -lt $num2 ];then
echo “$num1 小于 $num2”
else
echo “$num1 等于$num2”
fi
“`
#### 19 案例24-检查磁盘分区的情况
“`sh
[root@kylin shell]# sh 24.check_dis.sh | column -t -s ,
磁盘名字:/ 磁盘大小:145G 磁盘使用率:4 级别:正常
磁盘名字:/backup 磁盘大小:50G 磁盘使用率:1 级别:正常
磁盘名字:/boot 磁盘大小:1014M 磁盘使用率:17 级别:正常
[root@kylin shell]# cat 24.check_dis.sh
#!/bin/bash
##############################################################
# File Name: 24.check_dis.sh
# Version: V1.0
# Author: ysl
# Organization: www.ysledu.com
# Date: 2024-10-17 21:46:44
# Desc:
##############################################################
#1.vars
part_names=`df -h | grep -v tmpfs | awk ‘NR>=2{print $NF}’`
part_count=`df -h | grep -v tmpfs | awk ‘NR>=2{print $NF}’|wc -l`
#2.for
for name in $part_names
do
part_size=`df -h $name | awk ‘NR==2{print $2}’`
part_percent=`df -h $name | awk -F “[ %]+” ‘NR==2{print $(NF-1)}’`
if [ $part_percent -ge 95 ];then
waring=灾难
elif [ $part_percent -ge 90 ];then
waring=相当严重
elif [ $part_percent -ge 80 ];then
waring=严重
elif [ $part_percent -ge 70 ];then
waring=警告
else
waring=正常
fi
echo “磁盘名字:$name,磁盘大小:$part_size,磁盘使用率:$part_percent,级别:$waring”
done
[root@kylin shell]#
“`
条件表达式: -f -d -x -h, = != -z -n, -gt -ge -lt -le -eq -ne, -a -o ! ,[[ =~ ]]
if: 单分支,双分支,多分支.
#### 20 case语句
##### 1 概述
相当于是if中的字符串对比判断. (= !=) .比大小,文件,目录判断,正则只能使用if
类似于条件分支语句,case一般用于实现有多种选择的脚本(菜单选择)
这个功能:if或多分支if实现,如果使用case语句会更加清晰直观
菜单。
start|stop|restart|status
手写堡垒机.
环境部署脚本
case语句vs if多分支
case 一般用于固定的菜单选择情况.运行脚本用户输入1,2,3,4.
start|stop|restart….
if 可以用于一些范围的比较
##### 2 格式与实践
case “变量” in
1)
命令
;;
2)
命令
;;
*)
命令(保底的默认输出)
esac
##### 3 案例25-某会所菜单展示程序
“`sh
oldli会所的菜单功能(套餐)
– 输出可选的套餐
– 1 138套餐) 吃饱套餐
– 2 443套餐) 吃饱喝足套餐
– 3 888套餐) 吃喝拉撒套餐
– 4 1688套餐) 你想干啥就干啥套餐
– 5 8080套餐) 隐藏不便显示 隐藏
– 6 8443套餐) 隐藏老板娘套餐 隐藏
– 其他) 劝退套餐
cat<步骤–>函数–>命令。
把常用的判断,内容写成函数,创建个人函数库.(哪些功能通用的.)
函数传参:$* $@ $n $0
##### 6 个人函数库建立
“`sh
Linux命令行给字体加颜色命令为:
echo -e “\E[1;31m红色字ysl\E[0m”
红色字ysl
echo -e “\033[31m红色字ysl \033[0m”
\E 或\033 表示要开启这种功能。
[1;31m
[字体效果;颜色m
\E[0m 颜色设置结束
红色字ysl
在上述命令中:
echo -e可以识别转义字符,这里将识别特殊字
符的含义,并输出。 \n \t
Linux下面回车是 \n
Windows下面回车是 \r\n
各种颜色的字-效果
1表示加粗,2正常的,5表示闪烁
echo -e “\E[1;31m红色字ysl\E[0m”
echo -e “\E[2;31m红色字ysl\E[0m”
echo -e “\E[3;31m红色字ysl\E[0m”
echo -e “\E[4;31m红色字ysl\E[0m”
echo -e “\E[5;31m红色字ysl\E[0m”
echo -e “\E[6;31m红色字ysl\E[0m”
echo -e “\E[7;31m红色字ysl\E[0m”
echo -e “\E[8;31m红色字ysl\E[0m”
for n in {30..50}; do echo -e “\E[1;${n}m${n}ysl\E[0m”;done
“`
##### 7 案例31-用户自定义的函数库文件,自定义颜色
创建3个函数
redecho 内容 输出显示为红色闪烁
greenecho 内容 输出绿色加粗
yellowecho 内容 输出黄色加粗
redecho 内容
“`sh
#1.红色函数
function redecho() {
str=”$@”
echo -e “\E[5;31m${str}\E[0m”
}
#2.绿色函数
function greenecho() {
str=”$@”
echo -e “\E[1;32m${str}\E[0m”
}
#3.黄色函数
function yellowecho() {
str=”$@”
echo -e “\E[1;33m${str}\E[0m”
}
#4.蓝色函数
function blueecho() {
str=”$@”
echo -e “\E[1;34m${str}\E[0m”
}
“`
#### 22 核心命令
##### 1 命令概述
| 脚本常用监控命令 | 说明 | |
| —————- | ———————————— | ———————————————————— |
| 端口 | 一般用于检查端口是否存在,是否能连接 | 是否存在:ss/netstat -tunlp\|grep 端口,是否能访问:telnet , nc , nmap |
| 进程 | 检查进程状态,指标 | ps/top/iotop |
| 网络 | 检查连通性 | ping,iftop,dig |
| web | http请求 | curl/wget |
| 系统全能 | atop(all) | |
##### 2 是否存在
ss -tunlp | grep 80
netstat -tunlp | grep 80
lsof -i:80
##### 3 能否远程访问
telnet
nc -z -w 0.5
nmap -p端口过滤open即可
“`sh
telnet
-e指定逃脱字符,遇到这个字符相当于按ctrl+c.
[root@kylin shell]# echo q | telnet -eq 127.0.0.1 22
Telnet escape character is ‘q’.
Trying 127.0.0.1…
Connected to 127.0.0.1.
Escape character is ‘q’.
telnet> Connection closed.
[root@kylin shell]# echo $?
0
[root@kylin shell]#
nc(ncat netcat)
-z 无io模式,用于检查端口是否连通。 非交互模式.
-w 指定超时时间.
[root@kylin shell]# echo $?
0
[root@kylin shell]# nc -z -w 1 127.0.0.1 22
[root@kylin shell]# echo $?
0
[root@kylin shell]# nc -z -w 1 127.0.0.1 80
[root@kylin shell]# echo $?
1
[root@kylin shell]#
“`
##### 4 案例33-检查指定的地址的端口是否可以访问
“`sh
[root@kylin shell]# sh 33.check_port.sh 127.0.0.1 80
33.check_port.sh: 第 59 行:[: 缺少 `]’
不能访问
[root@kylin shell]# vim 33.check_port.sh
[root@kylin shell]# sh 33.check_port.sh 127.0.0.1 80
33.check_port.sh: 第 57 行:[: 缺少 `]’
不能访问
[root@kylin shell]# vim 33.check_port.sh
[root@kylin shell]# sh 33.check_port.sh 127.0.0.1 80
不能访问
[root@kylin shell]# sh 33.check_port.sh 127.0.0.1 22
可以访问
[root@kylin shell]# cat 33.check_port.sh
#!/bin/bash
##############################################################
# File Name: 33.check_port.sh
# Version: V1.0
# Author: ysl
# Organization: www.ysledu.com
# Date: 2024-10-19 10:32:05
# Desc:
##############################################################
#1.红色函数
function redecho() {
str=”$@”
echo -e “\E[5;31m${str}\E[0m”
}
#2.红色函数
function greenecho() {
str=”$@”
echo -e “\E[1;32m${str}\E[0m”
}
#2.vars
ip=$1
port=$2
#3判断参数个数
if [ ! $# -eq 2 ];then
greenecho “Usage:$0 IP或域名+端口”
exit 1
fi
#4.判断端口是否为数字
if [[ ! $port =~ ^[0-9]+$ ]];then
redecho “端口为数字”
exit 2
fi
#5.判断IP或域名是否通
ping -c3 -w3 $ip > /dev/null 2>&1
if [ $? -ne 0 ];then
redecho “无法访问$ip”
exit 3
fi
#6.检查是否有telnet命令
telnet_cmd=`which telnet | wc -l`
if [ $telnet_cmd -eq 0 ];then
redecho “没有telnet命令,请安装”
fi
#3.检查
function check() {
echo q | telnet -eq $ip $port >/dev/null 2>&1
if [ $? = 0 ] ;then
greenecho “可以访问”
else
redecho “不能访问”
fi
}
check
“`
##### 5 web与api测试命令
curl/wget
curl: -v -L跟随跳转 -H 修改请求头 -I 只显示响应头 -w 按照指定格式输出 –
o 输出指定到文件或空. -s一般使用管道需要加上
“`sh
#01 curl 获取状态码
#-s slient 安静模式 如果不使用默认输出下载进度
#-o curl的输出到指定位置的文件
#-w 按照指定格式与内容输出 %{http_code}状态码 更多格式 man curl 搜
索 variable
[root@kylin shell]# curl -L -s -I baidu.com |awk ‘NR==1{print $2}’
[root@kylin shell]# curl -L -s -I baidu.com
HTTP/1.1 200 OK
Date: Sat, 19 Oct 2024 02:39:49 GMT
Server: Apache
Last-Modified: Tue, 12 Jan 2010 13:48:00 GMT
ETag: “51-47cf7e6ee8400″
Accept-Ranges: bytes
Content-Length: 81
Cache-Control: max-age=86400
Expires: Sun, 20 Oct 2024 02:39:49 GMT
Connection: Keep-Alive
Content-Type: text/html
[root@kylin shell]# curl -L -s -w ‘%{http_code}\n’ -o /dev/null jd.com
200
“`
wget:
-t 失败后,重复尝试次数、
-T timeout 超时时间
-q quiet 不显示wget输出
–spider 不下载文件,仅访问
“`sh
[root@kylin shell]# wget -t 3 -T 1 -q –spider www.baidu.com
[root@kylin shell]# echo $?
0
[root@kylin shell]#
“`
##### 6 案例34-检查指定网站/api是否可以访问
“`sh
[root@kylin shell]# sh 34.check_url.sh www.baidu.com
网站www.baidu.com 可以访问
[root@kylin shell]# sh 34.check_url.sh 127.0.0.1:22
网站127.0.0.1:22 可以访问
[root@kylin shell]# sh 34.check_url.sh 127.0.0.1:80
网站127.0.0.1:80 不可以访问
[root@kylin shell]# cat 34.check_url.sh
#!/bin/bash
##############################################################
# File Name: 34.check_url.sh
# Version: V1.0
# Author: ysl
# Organization: www.ysledu.com
# Date: 2024-10-19 11:42:17
# Desc:
##############################################################
#颜色函数
#1.红色函数
function redecho() {
str=”$@”
echo -e “\E[1;31m${str}\E[0m”
}
#2.绿色函数
function greenecho() {
str=”$@”
echo -e “\E[1;32m${str}\E[0m”
}
#1.vars
curl_dizhi=$@
#2.for
function check_curl() {
for dizhi in $curl_dizhi
do
wget -p –spider $dizhi > /dev/null 2>&1
if [ $? -eq 0 ];then
greenecho “网站$dizhi 可以访问”
else
redecho “网站$dizhi 不可以访问”
exit 2
fi
done
}
#3.检查是否为空
function check_vars() {
if [ -z $curl_dizhi ];then
redecho “请输入地址”
exit 1
fi
}
main() {
check_vars
check_curl
}
main
“`
##### 7 案例35-检查域名是否过期
##### 8 案例36-:
“`sh
使用for循环在/ysl目录下通过随机小写10个字母加固定字
符串ysl批量创建10个html文件,名称例
如为:
[root@oldgirl C19]# ls /ysl
apquvdpqbk_ysl.html
mpyogpsmwj_ysl.html
txynzwofgg_ysl.html
bmqiwhfpgv_ysl.html
mtrzobsprf_ysl.html
vjxmlflawa_ysl.html
jhjdcjnjxc_ysl.html
qeztkkmewn_ysl.html
jpvirsnjld_ysl.html
ruscyxwxai_ysl.html
“`
##### 9 生成随机数字
mkpasswd -l -10 -s 0
-l 随机字符长度
-s 特殊字符个数
“`sh
[root@kylin shell]# mkpasswd -l -10 -s 0
-bash: mkpasswd:未找到命令
[root@kylin shell]#
[root@kylin shell]# yum install -y mkpasswd
上次元数据过期检查:1:33:30 前,执行于 2024年10月19日 星期六 10时17分46秒。
未找到匹配的参数: mkpasswd
错误:没有任何匹配: mkpasswd
[root@kylin shell]# yum provides mkpasswd
上次元数据过期检查:1:33:40 前,执行于 2024年10月19日 星期六 10时17分46秒。
expect-1:5.45.4-5.ky10.x86_64 : A tool for automating interactive applications
仓库 :ks10-adv-os
匹配来源:
文件名 :/usr/bin/mkpasswd
[root@kylin shell]# yum install -y expect-1:5.45.4-5.ky10.x86_64
上次元数据过期检查:1:34:02 前,执行于 2024年10月19日 星期六 10时17分46秒。
依赖关系解决。
=============================================================================================
Package Architecture Version Repository Size
=============================================================================================
安装:
expect x86_64 1:5.45.4-5.ky10 ks10-adv-os 237 k
事务概要
=============================================================================================
安装 1 软件包
总下载:237 k
安装大小:647 k
下载软件包:
expect-5.45.4-5.ky10.x86_64.rpm 404 kB/s | 237 kB 00:00
———————————————————————————————
总计 402 kB/s | 237 kB 00:00
运行事务检查
事务检查成功。
运行事务测试
事务测试成功。
运行事务
准备中 : 1/1
安装 : expect-1:5.45.4-5.ky10.x86_64 1/1
运行脚本: expect-1:5.45.4-5.ky10.x86_64 1/1
验证 : expect-1:5.45.4-5.ky10.x86_64 1/1
已安装:
expect-1:5.45.4-5.ky10.x86_64
完毕!
[root@kylin shell]# mkpasswd -l -10 -s 0
impossible to generate -10-character password with 2 numbers, 2 lowercase letters, 2 uppercase letters and 0 special characters.
[root@kylin shell]# mkpasswd -l 10
L?yi6qxCi4
[root@kylin shell]# mkpasswd -l 10 -s 0
nSrw8npuF3
“`
tr -cd ‘a-zA-Z0-9’ < /dev/urandom | head -c10
head -c10 取第一行的前10个字符
```sh
[root@kylin shell]# tr -cd 'a-zA-Z0-9' < /dev/urandom | head -c10
KZ9jEIPbB9
[root@kylin shell]#
[root@kylin shell]#
```
```sh
2.
debian/ubunt : 软件包叫:libstring-mkpasswd-perl mkpasswd.pl
红帽系列 软件包叫:expect
mkpasswd -l 10 -d 0 -s 0 -C 0
-l 密码长度
-d 数字数量
-s special 特殊字符
-C 大写字母
-c 小写字母
3.
tr
tr -cd 'a-z'