一、什么是shell
- Shell是linux的一外壳,它包在linux内核的外面,为用户和内核之间的交互提供了一个接口
- 当用户下达指令给操作系统的时候,实际上是把指令告诉shell,经过shell解释,处理后让内核做出相应的动作
- 系统的回应和输出的信息也由shell处理,然后显示在用户的屏幕上
二、什么是shell脚本
- 简单的说,当命令或者程序不在命令行执行,而是通过一个程序文件来执行,这个程序就被称为shell脚本
- 也就是在shell脚本里内置了多条命令,语句,循环控制,然后将这些命令一次性执行完毕,这种通过文件执行命令的方式称为非交互式
三、为什么使用shell脚本
- 适合处理操作系统底层的业务,有众多系统命令为其做支撑(还有文本处理三兄弟grep,sed,awk)
- 适合处理纯文本文件,linux中许多服务配置文件,启动脚本,都是纯文本(httpd,nfs,mysql,nginx,lvs)
- linux系统脚本用shell开发更简单
四、如何查看系统默认shell
三种方式:
[root@fuwu ~]# cat /etc/passwd | head -1
root:x:0:0:root:/root:/bin/bash
[root@fuwu ~]# grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@fuwu ~]# echo $SHELL
/bin/bash
五、shell脚本的建立及开发规范
一个完整的shell脚本需要有以下几个部分:
-
脚本名:最好以.sh结尾
-
第一行:#!/bin/bash
-
指定解释器:由哪个程序来执行脚本内容
-
#!:幻数
注意:#!/bin/bash必须写在第一行,否则会被认为是注释 -
有用户判断,否则任何用户都可以执行这个脚本
-
有流程控制,否则只是把简单的命令进行顺序操作,没有成功与否的判断
-
注释:可以命令后,也可以自成一行
例:清空日志[root@fuwu test]# cat log.sh #!/bin/bash #Date:2018-12-26 #Author:limin #Connect:123456789@qq.com #Desc: This script is for ... #Version:1.0 LOG_DIR=/var/log ROOT_UID=0 ##判断是否是超级用户 if [ "$UID" -ne "$ROOT_UID" ];then echo "Error:you should be root to run this script!" exit 1 fi ##判断能否进入目录 cd $LOG_DIR || { echo "Cannot access to directory." exit 1 } > messages && { echo "Logs cleaned up ..." exit 0 } [root@fuwu test]# sh log.sh Logs cleaned up ... [root@fuwu test]# cat /var/log/messages [root@fuwu test]#
六、脚本的执行方式
- bash script.sh或者 sh script.sh(当脚本没有执行权限时)
- path/script.sh或者 ./script.sh(绝对路径,或当前目录下,要给脚本一个执行权限)
- source script.sh 或者 . script.sh
(需要传递变量或函数时使用)
这种方式会使用source或.号来读如入指定shell文件,并会把其他shell中的变量值或函数返回给父shell继续使用
前两种方式,在执行脚本的时候,会默认打开一个新的shell,而新shell的变量值和函数不会返回给父shell
[root@fuwu ~]# cd /test/
[root@fuwu test]# ls
http.sh
[root@fuwu test]# vim http.sh
[root@fuwu test]# sh http.sh
A:start 开启httpd服务
B:stop 关闭httpd服务
C:restart 重启httpd服务
D:status查看httpd服务的状态
请输入你的选择:
[root@fuwu test]# bash http.sh
A:start 开启httpd服务
B:stop 关闭httpd服务
C:restart 重启httpd服务
D:status查看httpd服务的状态
请输入你的选择:
[root@fuwu test]# ls
http.sh
[root@fuwu test]# chmod +x http.sh
[root@fuwu test]# http.sh
bash: http.sh: command not found...
[root@fuwu test]# ls
http.sh
[root@fuwu test]# chmod +x http.sh
[root@fuwu test]# /test/http.sh
A:start 开启httpd服务
B:stop 关闭httpd服务
C:restart 重启httpd服务
D:status查看httpd服务的状态
请输入你的选择:
[root@fuwu test]# ./http.sh
A:start 开启httpd服务
B:stop 关闭httpd服务
C:restart 重启httpd服务
D:status查看httpd服务的状态
请输入你的选择:
[root@fuwu test]# source http.sh
A:start 开启httpd服务
B:stop 关闭httpd服务
C:restart 重启httpd服务
D:status查看httpd服务的状态
请输入你的选择:q
Connection to 172.25.254.160 closed.
[root@fuwu test]# . http.sh
A:start 开启httpd服务
B:stop 关闭httpd服务
C:restart 重启httpd服务
D:status查看httpd服务的状态
请输入你的选择:q
Connection to 172.25.254.160 closed.