一、基本概念

Shell概念

Shell也是操作系统中的一个软件。是一个命令行解释器。它包在Linux内核的外面,为用户和内核之间的交互提供了一个接口。系统中的命令用Shell去解释,Shell接收系统回应的输出并显示其到屏幕中。

Shell是面向对象的解释型语言。

Shell脚本概念

是一种为 shell 编写的脚本程序。也就是在Shell脚本里内置了多条命令,语句,循环控制,用脚本判定命令的执行条件,用脚本来实现动作的批量执行。

Shell脚本的优点

适合处理操作系统底层的业务,有众多系统命令为其做支撑(还有文本处理三兄弟grep,sed,awk);适合处理纯文本文件,linux中许多服务配置文件,启动脚本,都是纯文本(httpd,nfs,mysql,nginx,lvs);linux系统脚本用shell开发更简单。

二、Shell 脚本的创建

vim script.sh     ##必须以.sh结尾
#!/bin/bash       #脚本使用的解释器,通常用幻数"#!"指定
#AUTHOR           #脚本的作者
#DATE             #脚本创建时间
#MAIL             #脚本作者联系方式
#VERSION          #脚本的版本

脚本示例:

vim hello.sh
#!/bin/bash
#AUTHOR:  timoyang
#DATE:    2019-02-28
#MAIL:    yang.westos.com
#VERSION: 1.0
echo "hello world!"

Linux Shell编程——Shell基础知识

调用:

sh hello.sh
Linux Shell编程——Shell基础知识

三、脚本的调式

sh -x script.sh         ##适用于所有的Shell脚本

注意:Shell脚本必须有可执行权限 X
Linux Shell编程——Shell基础知识
Linux Shell编程——Shell基础知识
Linux Shell编程——Shell基础知识

四、Shell 脚本的执行

Shell 脚本有3种调用方式。

sh script.sh ##适用所有,用指定的sh去调用
Linux Shell编程——Shell基础知识

source script.sh ##用当前的环境去调用,不会开启新的Shell
Linux Shell编程——Shell基础知识

chmod +x script.sh ##加权限用脚本名去调用,绝对路径./script.sh
Linux Shell编程——Shell基础知识
Linux Shell编程——Shell基础知识

五、Shell 脚本的规范

vim /etc/vimrc
66 autocmd BufNewFile *.sh,*.script exec "call WESTOS()"   ##将map注释(当是次文件类型时,自动添加)
67 map <F5> ms:call WESTOS()<cr>'s      ##WESTOS是对调用的函数块的命名
68 function WESTOS()
69         call append(0,"#####################################")
70         call append(1,"# AUTHOR:      yang                 #")
71         call append(2,"# CREATE_DATE: ".strftime("%Y-%m-%d")."           #")
72         call append(3,"# VERSION:     1.0                  #")
73         call append(4,"# MAIL:        [email protected]      #")
74         call append(5,"# DESCRIPTION:                      #")
75         call append(6,"#####################################")
76 endfunction

脚本示例:

编写脚本:将/etc/下的所有以.conf结尾的备份到/mnt/backup/下,并让文件以.conf.月-日结尾

vim /mnt/backup.sh
#!/bib/bash
mkdir /mnt/backup
cp -p /etc/*.conf /mnt/backup/
cd /mnt/backup/
rename .conf .`date +%m-%d` *

Linux Shell编程——Shell基础知识
Linux Shell编程——Shell基础知识
Linux Shell编程——Shell基础知识
改正:因为用到的命令太多,故调整为以下

vim /mnt/backup.sh
#!/bin/bash
mkdir /mnt/backup
find /etc/ -name *.conf -exec cp -p {} /mnt/backup/ \;        #找到etc下所有以.conf结尾的文件,
find /mnt/backup/ -name *.conf -exec rename *.conf .`date +%m-%d` * \;

Linux Shell编程——Shell基础知识
Linux Shell编程——Shell基础知识

相关文章:

  • 2021-07-02
  • 2021-11-07
  • 2019-10-10
  • 2021-12-13
  • 2021-06-03
  • 2021-07-09
猜你喜欢
  • 2021-05-22
  • 2021-09-01
  • 2021-09-01
  • 2021-11-04
  • 2021-12-19
  • 2022-01-01
相关资源
相似解决方案