1. 前言
参考Springboot的启动脚本:
写了这个脚本,尝试写一下shell脚本
程序员正是为了懒而懒的....
脚本基础功能:
build:构建 start:启动 status:查询状态 restart:重启(会重新构建,比如代码更新了...)
最主要,在博客里面备份下脚本:
#!/bin/bash
RED="\033[31m"
GREEN="\033[32m"
YELLOW="\033[33m"
END="\033[0m"
echo $1 $2
if [ "$1" = "" ];then
echo -e "\033[0;31m 请输入操作名 \033[0m"
exit 1
fi
if [ ! -f "go.mod" ];
then
echo -e "go.mod文件不存在,请在项目目录运行..."
exit 1
fi
GoName=`head -n 1 go.mod| awk '{print $2}'`
function stop()
{
print_color_string 'red' "stopping..."
boot_id=`ps -ef | grep $GoName |grep -v grep|awk '{print $2}'`
count=`ps -ef |grep $GoName |grep -v grep|wc -l`
if [ $count != 0 ];then
kill $boot_id
count=`ps -ef |grep $GoName |grep -v grep|wc -l`
fi
print_color_string 'green' "stopped!"
}
function build()
{
if [ -f $GoName ]; then
print_color_string 'red' "deleting old execute file..."
rm -rf $GoName
fi
print_color_string 'green' "building...."
go build
if [ $? != 0 ] ;then
print_color_string 'red' "fail to build"
else
print_color_string 'green' "success to build"
fi
}
function start()
{
print_color_string 'green' "starting...."
if [ ! -f $GoName ]; then
print_color_string 'yellow' "no execute file, building...."
build
fi
nohup ./$GoName 1>/dev/null 2>&1 &
print_color_string 'green' "started!"
}
function status()
{
count=`ps -ef |grep $GoName |grep -v grep|wc -l`
if [ $count != 0 ];then
print_color_string 'green' "$GoName is running..."
else
print_color_string 'red' "$GoName is not running..."
fi
}
function restart()
{
build
stop
sleep 1
start
}
print_color_string(){
color=$1
string=$2
case $color in
red)
echo -e "$RED $string $END"
;;
green)
echo -e "$GREEN $string $END"
;;
yellow)
echo -e "$YELLOW $string $END"
;;
*)
echo $string
;;
esac
}
case $1 in
build)
build;;
stop)
stop;;
start)
start;;
restart)
restart;;
status)
status;;
*)
echo "你输入了一个错误的命令"
esac