1.什么是shell
- 脚本中命令的解释器
2.shell脚本的意义
- 记录命令执行的过程和执行逻辑,以便以后重复执行
- 脚本可以批量处理主机
- 脚本可以定时处理主机
3.如何创建shell脚本
#!/bin/bash
(幻数,在执行bash脚本的时候,内核会根据它来指定改用那个程序来解释脚本的内容)- vim自动添加脚本首部:
vim /etc/vimrc
map <F4> ms:call MYRTITLE() <cr>'s##按F4,执行这个函数
autocmd BufNewFile *.sh,*.script call MYRTITLE()##创建这些文件时,自动调用
func MYRTITLE()
call append(0,"######")
call append(1,"#Author:myr")
call append(2,"#Create_TIme: ".strftime("%Y/%m/%d"))
call append(3,"######")
call append(4,"#!/bin/bash")
endfunc
- 创建新文件的结果:
4.如何执行shell脚本
- 手动在环境中开启指定解释器
sh script.sh
- 直接在当前环境中运行shell中的指令不开启新的shell
source script.sh
. script.sh
- 开启脚本中指定的shell并使用此shell环境运行脚本中的指令
chmod +x script.sh
/xxx/xxx/script.sh
./script.sh
5.如何对脚本进行调试
sh -x /mnt/westos.sh
- + ##运行指令
- 不带+ ##命令运行的输出
脚本练习:
- ip_show.sh 网卡 显示当前的网卡ip
- host_messages.sh 显示当前主机的名称,ip登陆当前主机的用户 hostname: xxxxx
ipaddress: xxxx.xxxx.xxx.xxx
username: root
- clear_log.sh 执行次脚本后可以清空日志
- 进阶版本:
- 其中的指令: