【Linux】【Shell】主控脚本实现

研究学习 Linux Shell 的系列文章.

这篇文章主要讲 Shell 主控脚本的实现.

1. 内容介绍

在这里插入图片描述
.../monitor 目录下有如下4个shell脚本:

  • monoitor_man.sh:控制运行下面三个脚本.
  • system_monitor.sh:获取系统信息及运行状态.
  • check_server.sh:ngnix和mysql应用状态分析.
  • check_http_log.sh:应用日志分析.

Shell 系列研究学习的第8~11这4篇文章分别介绍这4个shell脚本的实现.

2. 相关知识

2.1 关联数组

在第4篇讲到declare命令时,提到过-a选项可以将shell变量声明为数组类型,更准确的来说是普通数组. 而使用-A选项可以将shell变量声明为关联数组.

  • -a 普通数组:只能使用整数作为数组索引.
  • -A 关联数组:可以使用字符串作为数组索引.
$ declare -A songs
$ songs[Bob]=bbb
$ songs[Ann]=xyz
$ echo ${songs[Ann]}
xyz
$ echo ${songs[Bob]}
bbb
$ echo ${songs[*]}
bbb xyz

2.2 `command`的作用

`command`$(command)的作用是一样的,将命令输出的内容保存在shell变量中.

$ ff=`ls`
$ echo $ff
anaconda-ks.cfg

2.3 tput sgr0 的作用

tput 命令将通过 terminfo 数据库对终端会话进行初始化和操作. 通过使用该命令,可以更改终端功能,如移动或更改光标、更改文本属性,以及清除终端屏幕的特定区域.

tput sgr0 表示关闭终端的所有属性. 在《控制 Bash 输出的格式与颜色》中介绍过使用转义序列控制字符串的颜色和格式. 在转义序列后面使用\e[0m取消样式,避免对后续内容的影响. 在颜色和格式控制中,tput sgr0\e[0m 的作用一致.

2.4 正则表达式匹配

前面文章介绍过正则表达式条件判断式. [[ A =~ B ]]用于判断正则表达式是否匹配,其中A是字符串,B是正则表达式. 如果A匹配B的模式,则[[ A =~ B ]]返回0;如果不匹配,返回1.

$ [[ 12345 =~ [0-9] ]] && echo 'match' || echo 'not match'
match
$ [[ abcde =~ [0-9] ]] && echo 'match' || echo 'not match'
not match

3. 脚本实现

#!/bin/bash
resettem=$(tput sgr0)
declare -A ssharray
i=0
numbers=""
for script_file in `ls -I "monitor_man.sh" ./`
do
    echo -e '\e[0;1;35m'"The Script:" ${i} '==>' ${resettem} ${script_file}
    grep -E "^\#Program function" ${script_file}
    ssharray[$i]=${script_file}
    numbers="${numbers} | ${i}"
    i=$((i+1))
done

while true
do
    read -p "Please input one number in [ ${numbers} ]:" execshell
    if [[ ! ${execshell} =~ ^[0-9]+ ]]; then
        exit 0
    fi
    /bin/sh ./${ssharray[$execshell]}
done
$ touch check_http_log.sh check_server.sh system_monitor.sh
$ bash monitor_man.sh 

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/RadiantJeral/article/details/111870045
今日推荐