文章目录
1.什么是shell
脚本中命令的解释器
Shell指“为使用者提供操作界面”的软件(命令解析器)。它类似于DOS下的command.com和后来的cmd.exe。它接收用户命令,然后调用相应的应用程序。
2.shell脚本的意义
1.记录命令执行的过程和执行逻辑,以便以后重复执行
2.脚本可以批量处理主机
3.脚本可以定时处理主机
3.如何创建shell脚本
3.1 !/bin/bash
一个规范的Shell脚本在第一行会指出由哪个程序(解释器)来执行脚本中的内容,这一行内容在Linux中的编程一般为
#!/bin/bash
或者
#!/bin/sh
开头的“#!"字符又称为幻数,在执行bash脚本的时候,内核会根据“#!”后面的解释器来确认哪个程序解释这个脚本中的内容
(注意:这一行必须写在每个脚本的第一行,即最优先执行的命令)
Linux中常用的解释器有:bash,sh,csh,tch等
UNIX中常用的解释器有:sh,kcsh等
3.2 vim自动添加脚本首部
在 /etc/vimrc配置文件中进行配置自动添加脚本首部
1.指定快捷键的方式添加脚本首部
map <F4> ms:call CVIMTITLE()<cr>'s ###快捷键指定方式
func CVIMTITLE()
call append (0,"#############################")
call append (1,"# Author: red")
call append (2,"# Version: ")
call append (3,"# Create_Time: ".strftime("%Y/%m/%d"))
call append (4,"# Mail: red@.org")
call append (5,"# Info: ")
call append (6,"#")
call append (7,"#############################")
call append (8,"")
call append (9,"#!/bin/bash")
endfunc
2.在新建脚本时自动添加脚本首部
注意:
1.此方式针对于新建的shell
2.以.sh .script结尾(可自己设定)
autocmd BufNewFile *.sh,*.script call CVIMTITLE() ###自动添加脚本首部
func CVIMTITLE()
call append (0,"#############################")
call append (1,"# Author: red")
call append (2,"# Version: ")
call append (3,"# Create_Time: ".strftime("%Y/%m/%d"))
call append (4,"# Mail: red@.org")
call append (5,"# Info: ")
call append (6,"#")
call append (7,"#############################")
call append (8,"")
call append (9,"#!/bin/bash")
endfunc
4.如何执行shell脚本
4.1 手动在环境中开启指定解释器
(不运行脚本文件中的幻数,在纯净环境中执行命令)
sh script.sh |
---|
4.2 直接在当前环境中运行shell中的指令不开启新的shell
(在当前shell中执行命令,以下两种用法相同,写法不同)
source script.sh |
---|
. script.sh |
4.3 开启脚本中指定的shell并使用此shell环境运行脚本中的指令
chmod +x script.sh
/xxx/xxx/script.sh |
---|
./script.sh |
5.如何对脚本进行调试
sh -x /xxx/script.sh |
---|
带 + :运行指令
不带+ :命令运行的输出
6.脚本练习
1.ip_show.sh 网卡 ——显示当前的IP
#!/bin/bash
[ -z "$1" ] && {
echo "Error:no interface name Please input interface following Script!"
exit
}
ifconfig $1 &>/dev/null || {
echo "Error:interface $1 is not found"
exit
}
ifconfig $1 | awk '/inet\>/{print $2}'
ps:过滤网卡的方式如下:
nmcli device status | awk '$2~/ethernet/{print $4}'
2.host_messages.sh 显示当前主机的名称,ip,登陆当前主机的用户
格式如下:
hostname: xxxxx
ipaddress: xxxx.xxxx.xxx.xxx
username: root
#!/bin/bash:
echo "hostname: `hostname`"
echo "ipaddress: `ifconfig $1 | awk '/inet\>/{print $2}'|head -n 1`"
echo "username: `whoami`"
3.clear_log.sh 执行次脚本后可以清空日志
注意:日志在 /etc/rsyslog.conf
在rhel8中
!/bin/bash
[ "`whoami`" = "root" ] || {
echo "Error: This script must run as root"
exit
}
for Log_Name in `awk '/./&&!/^#/&&!/"/&&$2~/^\/|^\-/{print $2}' /etc/rsyslog.conf | sed 's/-//g'`
do
> $Log_Name && {
echo $Log_Name is cleared.
}
done
在rhel7中
#!/bin/bash
[ "`whoami`" = "root" ] || {
echo "Error: This script must run as root"
exit
}
for Log_Name in $(awk '/./&&!/^#/&&!/^\$/&&$2~/^\/|^\-/{print $2}' /etc/rsyslog.conf | sed 's/-//g')
do
> $Log_Name && {
echo $Log_Name is cleared.
}
done