shell脚本的基础知识

  • 一、什么是shell
  • 二、shell脚本的意义
  • 三、.如何创建shell脚本
  • 1、幻数
  • 2、vim手动添加脚本首部
  • 3、自动调用函数
  • 四.如何执行shell脚本
  • 一、手动在环境中开启新的指定解释器
  • 二、直接在当前环境中运行shell中的指令不开启新的shell
  • 五、如何对脚本进行调试


一、什么是shell

脚本中命令的解释器

二、shell脚本的意义

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

三、.如何创建shell脚本

1、幻数

#!/bin/bash ##幻数(脚本运行时,最先开启的程序)

2、vim手动添加脚本首部

按F4能手动出现脚本首部

vim ~/.vimrc   ##编写子配置文件
map <F4> ms:call WESTOS()<cr>'s     ##F4即可调用程序
func WESTOS()      ##主程序
        call append(0,"###################")
        call append(1,"#!/bin/bash")
endfunc

shell脚本自动执行输入yes_vim


结果:

shell脚本自动执行输入yes_shell脚本_02

3、自动调用函数

vim ~/.vimrc

"map<F4> ms:call WESTOS()<cr>'s  ##加"表示注释掉
autocmd BufNewFile *.sh,*.script call WESTOS()   ##表示新建以.sh,.script结尾的函数时自动调用WESTOS程序。
func WESTOS()
  call append(0,"###############")
  call append(1,"#Create_Time:       ".strftime("%Y/%m/%d"))###在引号李添加内容用.去连接。
  call append(2,"#Author:      ck")
  call append(3,"###############")
  call append(4,"")
  call append(5,"#!/bin/bash")
endfunc

autocmd BufNewFile *.sh setlocal sw=2 ts=2 et ai  
##ts代表自动缩进,sw表示自动缩进的长度为2,ts表示table键会空两格。et表示把table键转换为空格,ai表示自动缩进。

shell脚本自动执行输入yes_linux_03


效果如下:

shell脚本自动执行输入yes_shell脚本自动执行输入yes_04

四.如何执行shell脚本

1、sh脚本指定开启的shell为bash

shell脚本自动执行输入yes_shell脚本自动执行输入yes_05

一、手动在环境中开启新的指定解释器

1、sh调用,开启新的sh

sh script.sh

shell脚本自动执行输入yes_shell脚本_06


2、绝对路径给予执行权力,开启脚本指定shell

chmod +x 1.sh 
/root/Desktop/1.sh

shell脚本自动执行输入yes_bash_07

二、直接在当前环境中运行shell中的指令不开启新的shell

两种执行方式

source script.sh
. script.sh

shell脚本自动执行输入yes_linux_08

五、如何对脚本进行调试

查看执行过程

sh -x /mnt/westos.sh

shell脚本自动执行输入yes_shell脚本_09


练习:

练习题1要求:

host_messages.sh 显示当前主机的名称,ip登陆当前主机的用户

hostname: xxxxx

ipaddress: xxxx.xxxx.xxx.xxx

username: root

#!/bin/bash
echo -e "hostname:\t\t $(hostname)" 
echo -e "hostname:\t\t $(ifconfig ens160 |awk '/inet\>/{print $2}')" 
echo -e "hostname:\t\t $USER"

效果:

shell脚本自动执行输入yes_shell脚本自动执行输入yes_10

练习题2要求
clear_log.sh 执行次脚本后可以清空日志

#!/bin/bash
[ "$USER" != "root" ]&&{
        echo "please run $0 with root !!"
        exit
}
[ ! -e "/var/log/messages" ] && {
        echo "no logfile here !!"
        exit
}
> /var/log/messages &&{
        echo logfile is cleared !!
}

结果:

shell脚本自动执行输入yes_linux_11