一、shell基础介绍
1.什么是shell
shell是脚本中命令的解释器,shell语言是一种解释型语言
2.shell脚本的意义
(1)记录命令执行的过程和执行逻辑,以便以后重复执行
(2)脚本可以批量处理主机
(3)脚本可以定时处理主机
二、shell脚本
3.如何创建shell脚本
#!/bin/bash %幻数,表示常量,脚本中最顶级的进程
用env bash是为了防止shell路径不固定的问题
可以在脚本顶部写#!/bin/env bash %用env去调用bash这个程序,这样可以自动检索系统的环境并调用它
vim自动添加脚本首部:
"map <F4> ms:call WESTOSTITLE()<cr>'s
autocmd BufNewFile *.sh,*.script call WESTOSTITLE()
func WESTOSTITLE()
call append(0,"###############################################")
call append(1,"# Author: lee")
call append(2,"# Version: ")
call append(3,"# Create_Time: ".strftime("%Y/%m/%d"))
call append(4,"# Mail: lee@westos.org")
call append(5,"# Info: ")
call append(6,"# ")
call append(7,"################################################")
call append(8,"")
call append(9,"#!/bin/bash")
endfunc
4.如何执行shell脚本
(1)手动在环境中开启指定解释器
sh script.sh
(2)直接在当前环境中运行shell中的指令不开启新的shell
source script.sh
. script.sh
(3)开启脚本中指定的shell并使用此shell环境运行脚本中的指令
chmod +x script.sh %赋予脚本执行权限后可直接用绝对路径的方式以脚本中的指定shell调用脚本
/xxx/xxx/script.sh %注意:这里必须是绝对路径
./script.sh
5.如何对脚本进行调试
sh -x /mnt/westos.sh
+ %运行指令
不带+ %命令运行的输出
三、脚本练习
1、ip_show.sh 网卡 显示当前的主机ip
#!/bin/bash
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 "hostname: `hostname`"
echo "ipaddress: $(ifconfig enp1s0|awk '/inet\>/{print $2}')" %或者是echo "ipaddress: `(ifconfig enp1s0 | awk '/inet\>/{print $2}')`"
echo "username: $USER"
3、clear_log.sh 执行次脚本后可以清空日志
#!/bin/env bash
[ "$USER" = "root" ] || {
echo -e "\033[31mError: Please run script with root !!\033[0m"
exit 1
}
LOGS=`sed -n '/RULES/,$p' /etc/rsyslog.conf | awk '!/^#|^$/&&/var/{print $2}' | sed 's/-//g'`
for LOG in $LOGS
do
> $LOG && echo -e "\033[32m$LOG is cleared !!\033[0m"
done