shell脚本的基础知识

1.什么是shell

脚本中的命令解释器

2.shell脚本的意义

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

3.如何创建shell脚本

【1】幻数

#!/bin/bash     幻数(指定我们系统当中的解释器)
#! 是一个约定的标记,它告诉系统这个脚本需要什么解释器来执行,即使用哪一种Shell。

【2】自动添加脚本首部
vim /etc/vimrc

  • 在新脚本中按下F4:
map <F4> ms:call WESTOSTITLE()<cr>'s
func WESTOSTITLE()
        call append(0,"##################")
        call append(1,"# Author:   ")
        call append(2,"# Mail:     ")
        call append(3,"# Version:  ")
        call append(4,"# Create_Time:    ".strftime("%Y-%m-5d"))
        call append(5,"# Description:  ")
        call append(6,"")
        call append(7,"##################")
        call append(8,"")
        call append(9,"#!/bin/bash")
endfunc

在这里插入图片描述

在这里插入图片描述

按下F4即可:
在这里插入图片描述

  • 自动识别新脚本,无需按下F4
autocmd BufNewFile *.sh,*.script call WESTOSTITLE()
func WESTOSTITLE()
        call append(0,"##################")
        call append(1,"# Author:   ")
        call append(2,"# Mail:     ")
        call append(3,"# Version:  ")
        call append(4,"# Create_Time:    ".strftime("%Y-%m-5d"))
        call append(5,"# Description:  ")
        call append(6,"")
        call append(7,"##################")
        call append(8,"")
        call append(9,"#!/bin/bash")
endfunc

在这里插入图片描述
建立新的以.sh,或者.script结尾的文件时会自动添加:

在这里插入图片描述

4.如何执行shell脚本

【1】手动在环境中开启指定解释器

sh script.sh

该方法无论脚本有无执行权限,都可以执行,会开启一个子shell
【2】直接在当前环境中运行shell中的指令,该方法运行脚本时不会开启子shell,会在当前shell中运行

source script.sh
. script.sh

【3】开启脚本中指定的shell并使用此shell环境运行脚本中的指令

chmod +x script.sh    #用当前解释器
/xxx/xxx/script.sh
./script.sh

5.如何对脚本进行调试

sh -x /mnt/westos.sh
+x                 ##运行指令
不带+x             ##命令运行的输出

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

脚本练习

【1】执行westos.sh 显示当前的主机名称

#!/bin/bash
ifconfig ens160 &> /dev/null &&{
        ifconfig ens160 | awk '/inet\>/{print $2}'
} || {
        echo ens160 is not found
}
hostname

在这里插入图片描述

在这里插入图片描述
【2】host_messages.sh 显示当前的主机名称,ip登录当前主机的用户
hostname: xxxxx
ipaddress: xxxxx.xxxx.xxxx
username: root

#!/bin/bash
echo "hostname:   `hostname`"
echo "ipaddrshow: `ifconfig ens160 | awk '/inet\>/{print $2}'`"
echo "username:   `whoami`"

在这里插入图片描述
在这里插入图片描述
【3】执行脚本后可以清空日志

#!/bin/bash
[ "$USE" = "root" ] && {
find /var/log -maxdepth 1 -type f -exec cp /dev/null {} \;
}||{
        echo $0 is must be used by root
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值