1、什么是shell
脚本中命令的解释器
2、shell脚本的意义
1.记录命令执行的过程和执行逻辑,以便以后重复执行
2.脚本可以批量处理主机
3.脚本可以定时处理主机
3、如何创建shell脚本
#!/bin/bash ##幻数
vim自动添加脚本首部
打开vim 按F4可以获取所设置内容
[root@westos111 ~]# vim ~/.vimrc
[root@westos111 mnt]# cat ~/.vimrc
set nu ts=2 sw=2 et ai
map <F4> ms:call WESTOSSHELL()<cr>'s
func WESTOSSHELL()
call append(0,"###############################")
call append(1,"# Author: ")
call append(2,"# Version: ")
call append(3,"# CreateTime: ".strftime("%Y-%m-%d"))
call append(4,"# Mail: ")
call append(5,"# INFO: ")
call append(6,"###############################")
endfunc
打开sh或script结尾的文件自动获取设置内容
[root@westos111 mnt]# cat ~/.vimrc
set nu ts=2 sw=2 et ai
"map <F4> ms:call WESTOSSHELL()<cr>'s
autocmd BufNewFile *.sh,.script call WESTOSSHELL()
func WESTOSSHELL()
call append(0,"###############################")
call append(1,"# Author: ")
call append(2,"# Version: ")
call append(3,"# CreateTime: ".strftime("%Y-%m-%d"))
call append(4,"# Mail: ")
call append(5,"# INFO: ")
call append(6,"###############################")
endfunc
4、如何执行shell脚本
(1)手动在环境中开启指定解释器
sh script.sh
(2)直接在当前环境中运行shell中的指令不开启新的shell
source script.sh
. script.sh
(3)开启脚本中指定的shell并使用此shell环境运行脚本中的指令
chmod +x script.sh
/xxx/xxx/script.sh
./script.sh
5、如何对脚本进行调试
sh -x /mnt/westos.sh
+ ##运行指令
不带+ ##命令运行的输出
脚本练习:
(1)ip_show.sh 网卡 显示当前的IP
[root@westos111 mnt]# cat ip_show.sh
#!/bin/bash
[ -z "$*" ] && {
echo please input dev
exit
}
DEV_MASSAGE=$( ifconfig "$*" 2> /dev/null )||{
echo $* is not exist!!
}&&{
echo $DEV_MASSAGE | awk '/inet\>/{print$6}'
}
(2)host_messages.sh 显示当前主机的名称,ip登陆当前主机的用户
hostname: xxxxx
ipaddress: xxxx.xxxx.xxx.xxx
username: root
[root@westos111 mnt]# cat host_messages.sh
###############################
# Author:
# Version:
# CreateTime: 2021-11-23
# Mail:
# INFO:
###############################
#!/bin/bash
echo -e "hostname: \t $HOSTNAME"
echo -e "ipaddress: \t `ifconfig ens3 | awk '/inet\>/{print $2}'`"
echo -e "username:\t $USER"
如果有多个网卡时
[root@westos111 mnt]# cat host_messages.sh
#!/bin/bash
echo -e "hostname: \t $HOSTNAME"
for NETDEV in `awk -F : '/:/&&!/lo/{print $1}' /proc/net/dev`
do
echo -e "$NETDEV\tipaddress: \t `ifconfig ens3 | awk '/inet\>/{print $2}'`"
done
echo -e "username:\t $USER"
(3)clear_log.sh 执行次脚本后可以清空日志
思路:首先判定用户是否为root,如果不是需要提醒用户切换。如果是,在配置文件中截取日志的所有类型,然后清空。
判定用户是否为root:
配置文件中,日志目录都在RULES下,先过滤出RULES到最后一行
grep -A `sed -n $= /etc/rsyslog.conf` RULES /etc/rsyslog.conf
筛选不是以#开头的 awk '!/^#/{print $0}'
过滤所有空行并输出第二列awk '!/^#|^$/{print $2}'
过滤掉:开头的行,并将 - 改为空。到此筛选出了所有日志文件
完整代码:
[root@westos111 mnt]# cat clear_log.sh
#!/bin/bash
[ "$USER" != "root" ] && { ##判定用户是否为root
echo "please run $0 with root!!"
exit
}
for MESSAGES_FILE in `grep -A $(sed -n $= /etc/rsyslog.conf) RULES /etc/rsyslog.conf | awk '!/^#|^$|:/{print $2}' |sed 's/-//g'` ##筛选所有日志目录
do
> $MESSAGES_FILE ##用for循环将每个日志目录清空
done