【参考小例】
注意:Linux安装redis和部署(参考)
该脚本包含以下4点:
- 检查redis的后台启动配置。
- 检查当前redis运行状态。
- 如果redis未启动,则启动redis后台服务。如果redis已经启动,则返回redis已经在运行。
执行命令:bash myredis.sh start - 退出时关闭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