一.基础知识
1.什么是shell?
1)shell是里努西的一外壳,它包在linux内核的外面,为用户和内核之间的交互提供了一个接口
2)当用户下达指定个操作系统的时候,实际上是把指令告诉shell,经过shell解释,处理后让内核做出相应的动作
3)喜用的回应和输出的信息也由shell处理,然后显示在用户的屏幕上
什么是shell脚本?
1)简单的来说,当命令或者程序不在命令行执行,二是通过一个程序文件来执行,这个程序就被称为shell脚本
2)也就是在shell脚本里内置了多条命令,语句,循环控制,然后将这些命令一次性执行完毕,这种通过文件执行命令的方式称为非交互式
2.为什么使用shell脚本?
1)时和处理操作系统底层的业务,由众多系统命令为其作支撑(还有文本处理三兄弟grep,sed,awk)
2)时和处理纯文本文件,linux中许多服务配置文件,启动脚本,都是纯文本(httpd,nfs,mysql,nginx,lvs)
3)linux系统脚本用shell开发更简单
3.如何查看系统默认shell?(面试题)
方法1:
[root@localhost mnt]# echo $SHELL
/bin/bash
方法2:
[root@localhost mnt]# grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
4.脚本开发规范
一个完整的shell脚本需要以下几个部分:
1)脚本名:最好以.sh结尾
2)第一行:#!/bin/bash
指定解释器:由哪个程序来执行脚本内容
#!:幻数
注意:#!/bin/bash必须写在第一行,否则会被认为是注释
3)有用户判断,否则任何用户都可以执行这个脚本
4)有流程控制,否则只是把简单的命令进行顺序操作,没有成功与否的判断
5)注释:可以放在命令后,也可以自成一行(方便阅读脚本的人)
[root@localhost mnt]# vim test.sh
[root@localhost mnt]# cat test.sh
#!/bin/bash
#DATE:2018-12-22
#AUTHOR:westos-dz
#connect:[email protected]
#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
}
cat /dev/null > messages && {
echo "LOGS cleaned up..."
exit 0
}
echo "Logs cleaned failed..."
exit 1
5.脚本执行方法
1)sh test.sh | bash test.sh ##没有执行权限时
[root@localhost mnt]# sh test.sh
LOGS cleaned up...
2)path/test.sh | ./test.sh ##绝对路径,需要先给脚本添加执行权限
[root@localhost mnt]# pwd
/mnt
[root@localhost mnt]# /mnt/test.sh
-bash: /mnt/test.sh: Permission denied
[root@localhost mnt]# chmod +x /mnt/test.sh
[root@localhost mnt]# /mnt/test.sh
LOGS cleaned up...
3)source test.sh | .test.sh
这种方式会使用source或者.号来读如入指定shell文件,并会把其它shell中的变量值或函数返回给父shell继续使用
前两种方式,在执行脚本的时候,会默认打开一个新的shell,而新hsell的变量值和汉书不会返回给父shell
[root@localhost mnt]# vim source.sh
[root@localhost mnt]# cat source.sh
#!/bin/bash
username=`whoami`
[root@localhost mnt]# sh source.sh
[root@localhost mnt]# echo $username
[root@localhost mnt]# source source.sh
[root@localhost mnt]# echo $username
root