一、shell脚本
shell是脚本中命令的解释器。shell脚本可以记录命令执行的过程和执行逻辑以便以后重复执行,可以批量处理主机或者定时处理主机。
二、脚本的编写
1. 幻数
#!/bin/bash ##脚本执行环境
幻数是脚本运行中最先运行的指令,通常指定脚本的运行环境。
2. 设置vim运行时的行号与Tab建
vim ~/.vimrc ##只对当前用户生效
set nu ts=2 et ai ##set nu 显示行号,ts=2 Tab键为两个空格,et Tab键转换为空格,ai 自动缩进
vim /etc/vimrc ##在此文件下添加可对所有用户生效
3. 自动添加脚本首部
vim ~/.vimrc ##只对当前用户生效
set nu ts=2 et ai ##set nu 显示行号,ts=2 Tab键为两个空格,et Tab键转换为空格,ai 自动缩进
autocmd BufNewFile *.sh,*.script call SHELLTITLE() ##编写以.sh和.script结尾的新文件自动显示
func SHELLTITLE()
call append(0,"###############################################")
call append(1,"# Author: wy") ##作者
call append(2,"# Version: 2.0") ##版本
call append(3,"# Create_Time: ".strftime("%Y/%m/%d")) ##抓取时间
call append(4,"# Mail: wy@westos.org") ##邮箱
call append(5,"# Info: ")
call append(6,"# ")
call append(7,"################################################")
call append(8,"")
call append(9,"#!/bin/bash")
endfunc
三、脚本的执行
若现有一脚本/mnt/test.sh
source /mnt/test.sh ##在当前shell中运行脚本的命令
. /mnt/test.sh ##同上
sh /mnt/test.sh ##在指定的shell中运行脚本的命令
chmod +x /mnt/test.sh ##给脚本加上可执行权限
/mnt/test.sh ##在脚本中指定的shell中运行脚本的命令
四、对脚本进行调试
sh -x /mnt/test.sh ##显示命令及指令运行的输出
带+的是运行的指令,不带+的是输出
练习:
1. ip_show.sh 网卡 显示当前的ip
#!/bin/bash
[ -z "$1" ] && {
echo "Error : Please input interface following script!!!"
exit
}
ifconfig $1 &> /dev/null || {
echo $1 is not find
exit
} && {
ifconfig $1 | awk '/\<inet\>/{print $2}'
}
2. host_messages.sh 显示当前主机的名称、ip和登陆当前主机的用户
hostname: xxxxx
ipaddress: xxxx.xxxx.xxx.xxx
username: root
#!/bin/bash
echo "hostname: `hostname`"
echo "ipaddress: `ifconfig ens3|awk '/\<inet\>/{print $2}'`"
echo "username: $USER"
3. clear_log.sh 执行次脚本后可以清空日志
#!/bin/bash
[ "$USER" != "root" ] && {
echo "Error: Please run script with root!"
exit
}
[ ! -e "/var/log/messages" ] && {
echo "Error:not found log file!"
exit
}
> /var/log/message && {
echo "/var/message is cleaned !!"
}