Shell脚本实现自动检测/配置/开启/关闭redis后台服务

【参考小例】
注意:Linux安装redis和部署(参考)
该脚本包含以下4点:

  1. 检查redis的后台启动配置。
  2. 检查当前redis运行状态。
  3. 如果redis未启动,则启动redis后台服务。如果redis已经启动,则返回redis已经在运行。
    执行命令:bash myredis.sh start
  4. 退出时关闭redis服务。
    执行命令:bash myredis.sh stop
#!/bin/bash
cmd=$1
redisDir=/usr/local/redis

# 检查redis.conf
checkRedisConf(){
    confile=$redisDir/etc/redis.conf
    conf=`cat $confile | grep "daemonize no"`
    if [ ! -z "$conf" ]; then
        if [[ "$conf" =~ "#" ]]; then
            sed -i '/daemonize no/ s/^#//' $confile
            sed -i 's/daemonize no/daemonize yes/' $confile
            conf=`cat $confile | grep "daemonize yes"`
            if [ -z "$conf" ]; then
                echo "redis.conf 配置失败!"
            echo
                echo "redis.conf 配置成功!"
            fi 
        fi
    else
        conf=`cat $confile | grep "daemonize yes"`
        if [ -z "$conf" ]; then
                echo "redis.conf 配置失败,请检查配置文件:$confile"
            echo
                echo "redis.conf 配置成功!"
            fi 
    fi
}

startRedis(){
    cd $redisDir/etc
    redis-server redis.conf
    state=`netstat -anp | grep 6379 | grep -w tcp | grep -w LISTEN`
    if [ -z "$state" ]; then
        echo "Redis启动失败,请检查!"
    else
        echo "Redis已启动,请输入'redis-cli'进入redis访问!"
    fi
}

stopRedis(){
    cd $redisDir/bin
    redis-cli shutdown
    state=`netstat -anp | grep 6379 | grep -w tcp | grep -w LISTEN`
    if [ -z "$state" ]; then
        echo "Redis已关闭!"
    else
        echo "Redis关闭失败,请检查!"
    fi
}

# 检查当前redis状态
checkState(){
    nowState=`netstat -anp | grep 6379 | grep -w tcp | grep -w LISTEN`
    if [ -z "$nowState" ]; then
        echo "Redis 未启动!"
    else
        echo "Redis 正在运行,不用重复启动!"
        exit 0
    fi

}

echo "命令格式为:脚本.sh start/stop"
if [ -z "$cmd" ]; then
    echo "输入脚本命令:start or stop"
    read cmd
else
    echo "检查redis.conf配置"
    checkRedisConf
    if [ "$cmd" == "start" ]; then
        checkState
        startRedis
    elif [ "$cmd" == "stop" ]; then
        stopRedis
    else
        echo "输入的命令有误:start or stop,请检查!"
        exit 1
    fi
fi

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值