Background
以Redis服务为例,该shell脚本可以通过传入不同的参数实现服务的启动、停止、服务运行状态查看、服务运行日志查看和进入服务shell命令界面等功能。
直接上脚本operator.sh
用法可以使用
help
参数查看哈,用法例如:
先赋执行权限chmod +x operator.sh
查看帮助命令operator.sh help
#!/bin/bash
#
# 服务基本信息
operate=$1
ps_1='./redis-server'
pid_1=`ps -ef | egrep "$ps_1" | egrep -v grep | awk '{print $2}'`
dir_home=/usr/redis/
dir_log=/usr/redis/redis-server.log
# 判断输入参数
if [[ -z $operate || $operate = "help" ]]; then
echo '#####'
echo "please input your operate [run|stop|status|log|shell]"
echo '#####'
fi
# 启动服务
if [[ $operate = "run" || $operate = "start" ]]; then
rm -rf $dir_log
nohup $dir_home/bin/redis-server $dir_home/redis.conf >> $dir_log 2>&1 &
# 停止服务
elif [[ $operate = "stop" ]]; then
kill -9 $pid_1
# 查看服务运行状态
elif [[ $operate = "status" ]]; then
if [[ $pid_1 ]]; then
# 黄底蓝字
echo -e "\033[43;34m RUNNING \033[0m"
else
# 蓝底黑字
echo -e "\033[44;30m STOPPED \033[0m"
fi
# 查看服务运行日志
elif [[ $operate = "log" ]]; then
if [[ -e $dir_log ]]; then
tail -f $dir_log
else
echo '#####'
echo "No logs have been generated so far"
echo '#####'
fi
# 进入服务命令行界面
elif [[ $operate = "shell" ]]; then
if [[ $pid_1 ]]; then
$dir_home/bin/redis-cli -h Cloud09 -p 6379
else
echo '#####'
echo "The redis service has not been started yet"
echo '#####'
fi
fi