1.什么是shell?
shell 也是操作系统中的一个软件,它包在 linux 内核的外面,为用户和内核之间的交互提供
了一个接口系统中的命令用 shell 去解释,shell 接收系统回应的输出并显示其到屏幕中。
bash = GNU Bourne-Again Shell
2.什么是shell脚本?
脚本是一种解释型语言,用 shell 脚本保存执行动作;用脚本判定命令的执行条件;用脚本来实现动作的批量执行。
3.如何创建新shell脚本?
vim script.sh ## 用 vim 编写脚本
#!/bin/bash ##脚本使用的解释器,通常用幻数 "#!" 指定
#AUTHOR ##脚本作者
#DATE ## 脚本创作时间
#MAIL ##脚本作者联系方式
#VERSION ##脚本的版本
4.脚本示例
vim test.sh
#!/bin/bash
#AUTHOR:timinglee
#VERSION:1.0
#MAIL:timinglee@westos.org
#DATE:xxxx-xx-xx
echo "hello world!"
5.脚本的调式
参数 | 说明 |
---|---|
-n | 只读取shell脚本,但不执行 。测试脚本是否存在语法错误 |
-x | 进入跟踪方式,显示所执行的每一条命令 ,使shell在执行脚本的过程中把它实际执行的每一个命令行显示出来 |
-c | 从strings中读取命令 临时测试一小段脚本的执行结果 |
-v | 一边执行脚本,一边将执行过的脚本命令打印到标准输出。 |
sh -x scritps.sh
vim scripts.sh 适用于所有 shell 脚本
#!/bin/bash -x shell 脚本必须有 X 权限
6.脚本的执行
shell脚本执行的四种方法:
sh script.sh
source script.sh
. script.sh
chmod +x script.sh
./script.sh
- sh test.sh
- source test.sh
- . test.sh
- ./test.sh(这里的.指的是当前位置下即/mnt)
由上可得:
sh test.sh=/mnt/test.sh
source test.sh=. test.sh
注意:sh 和./执行shell脚本时会新开一个shell;source 和. 执行shell脚本时,在当前shell执行。
也可由下面操作来证明
小测试:
在虚拟机中执行 clear_log.sh,要求:脚本执行后系统日志清空。
日志文件配置目录:/etc/rsyslog.conf
为了证明实验完成,我们需在日志配置目录里将写入所有日志采集到/mnt/westos这一指定文件里。
vim /etc/rsyslog.conf
ssytemctl restart rsyslog.service
#!/bin/bash
Max_Line=`sed -n '$=' /etc/rsyslog.conf`
Target_Log=`grep RULES /etc/rsyslog.conf -A $Max_Line | awk '!/^#/&&!/^$/{print $2}'|sed '/^:/d;s/-//g'`
echo $Target_Log
for Log_File in $Target_Log
do
> $Log_File && {
echo $Log_File is clear !!
}
done
这个脚本所有用户都可以执行,不安全所以我们需指定root用户才可以清空日志。
[ "$USER" = "root" ] ||{
echo "Error : This script must run as root !!"
exit
}
Max_Line=`sed -n '$=' /etc/rsyslog.conf`
Target_Log=`grep RULES /etc/rsyslog.conf -A $Max_Line | awk '!/^#/&&!/^$/{print $2}'|sed '/^:/d;s/-//g'`
echo $Target_Log
for Log_File in $Target_Log
do
> $Log_File && {
echo $Log_File is clear !!
}
done