一.什么是shell
脚本中命令的解释器
脚本:可运行的纯文本
二.shell脚本的意义
1.记录命令执行的过程和执行逻辑,以便以后重复执行
2.脚本可以批量处理主机
3.脚本可以定时处理主机
三.如何创建shell脚本
#!/bin/bash ##幻数:C语言术语,可以直接使用的常数
vim自动添加脚本首部
vim ~/.vimrc ##编辑用户家目录下.vimrc,每个用户都可以自己DIY自己的脚本首部
1 set nu ##显示行号
2 set ts=2 ##tab键两个空格
3 func SCRIPT() ##添加脚本首部的函数
4 call append(0,"################")
5 call append(1,"#Author: lee")
6 call append(2,"#Version: ")
7 call append(3,"#Create_TIime: ".strftime("%Y-%m-%d"))
8 call append(4,"#Mail: lee@westos.org")
9 call append(5,"#Info: 测试脚本")
10 call append(6,"#")
11 call append(7,"################")
12 call append(8,"")
13 call append(9,"#!/bin/bash")
14 endfunc
15 map <F4> ms:call SCRIPT()<cr>'s ##编辑时快捷键调用
16
17 autocmd BUFNEWFILE *.sh,*.script.sh call SCRIPT() ##编辑文件名以.sh或.script结尾的自动生成脚本首部
四.如何执行shell脚本
1).手动在环境中开启指定解释器
sh test.sh
2).直接在当前环境中运行shell中的指令不开启新的shell
source test.sh
. test.sh
3).开启脚本中指定的shell并使用此shell环境运行脚本中的指令
chmod +x test.sh
/mnt/test.sh
./test.sh
五.如何对脚本进行调试
sh -x /mnt/test1.sh
+ ##运行指令
不带+ ##命令运行的输出
练习:
1.ip_show.sh 网卡 显示当前的主机IP
10 #!/bin/bash
11 [ -z "$1" ]&&{
12 echo -e "\033[31mError:Please input wangka!!\033[0m"
13 exit
14 }
15 ifconfig $1 &>/dev/null && {
16 ifconfig $1 | awk '/inet\>/{print $2}'
17 }||{
18 echo -e "\033[31mError:$1 is not exist!!\033[0m"
19 }
2.host_messages.sh 显示当前主机的名称,ip登陆当前主机的用户
hostname: xxxxx
ipaddress: xxxx.xxxx.xxx.xxx
username: root
11 hostname
12 ifconfig enp1s0 | awk '/inet\>/{print $2}'
13 id -nu
3.clear_log.sh 执行次脚本后可以清空日志
10 #!/bin/bash
11 [ $USER = root ] || {
12 echo 'Please change user to root'
13 exit
14 }
15 LOG=$(sed -ne 's/-//g' -e '/\/var\/log/p' /etc/rsyslog.conf | awk '{print $ 2}')
16 for i in $LOG
17 do
18 > $i
19 done