初识shell脚本——基础知识

1. shell

Shell 是指一种应用程序,这个应用程序提供了一个界面,用户通过这个界面访问操作系统内核的服务,是脚本中命令的解释器。

2. shell脚本的意义

 记录命令执行的过程和执行逻辑,以便以后重复执行
 脚本可以批量处理主机
 脚本可以定时处理主机

3. 如何创建shell脚本

#!/bin/bash ## 幻数,#! 用来指定系统中的解释器
在这里插入图片描述

3.1 vim自动添加脚本首部

vim /etc/vimrc

"map <F4> ms:call MYTITLE()<cr>'s                ## 手动添加,按F4增加首部
autocmd BufNewFile *.sh,*.script call MYTITLE()  ## 自动添加,针对新文件、.sh或.script结尾的文件自动添加首部## MYTITLE函数体,即自动添加部分
func MYTITLE()       
	call append(0,"###############")        
	call append(1,"# Author:          ")        
	call append(2,"# Version: 		   ")        
	call append(3,"# Create_Time: ".strftime("%Y/%m/%d"))        
	call append(4,"# Mail:  		   ")        
	call append(5,"# Description:      ")        
	call append(6,"#				   ")        
	call append(7,"###############")        
	call append(8,"")        
	call append(9,"#!/bin/bash")
endfunc

在这里插入图片描述

4. 如何执行shell脚本

(1)手动在环境中开启指定解释器
sh script.sh ## 脚本本身的解释器没有开启,该方法是在shell下开启一个子shell来执行内部操作
在这里插入图片描述

(2)直接在当前环境中运行shell中的指令不开启新的shell
source script.sh
或. script.sh
在这里插入图片描述
在这里插入图片描述

(3)开启脚本中指定的shell,并使用此shell环境运行脚本中的指令
chmod +x script
/xxx/xxx/script./script.sh
在这里插入图片描述

5. 如何对脚本进行调试

sh -x /mnt/dsd.sh
+ ##表示运行指令
不带+ ##表示命令运行的输出
在这里插入图片描述

6. 脚本练习

实验一:ip_show.sh显示当前主机IP和名称

#!/bin/bash
ifconfig "$1" | awk '/inet\>/{print $2}'
hostname

在这里插入图片描述

实验二:host_messages.sh 显示当前主机的名称、ip以及当前主机的用户

#!/bin/bash
echo "hostname:  `hostname`"
ifconfig `nmcli device status | awk '$2~/ethernet/{print $4}'` | awk '/inet\>/{print "ipaddress:" $2}'
ehco “ipaddress: ‘ifconfig br0 | awk ‘/inet\>/{print $2}’’”
echo "username:  `whoami`"
 

在这里插入图片描述

实验三:clear_log.sh 执行此脚本之后清空日志
cat /etc/sysconfig/rsyslog ## 查询日志文件

#!/bin/bash
[ "`whoami`" = "root" ] || {	
echo "You are not qualified,This script must be run in 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
 

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值