启动程序shell,并将程序放在后台运行

本文介绍了一种使用Shell脚本来管理后台进程的方法,包括检查进程是否运行、终止进程及重启进程的功能。通过改进版本,实现了更优雅的日志管理和进程控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/bin/bash
#参数个数小于或者大于 2 都报错
if [ $# -lt 2 ]; then
    echo 1>&2 "usage: $0 <webtest> <port>"
    exit 2
elif [ $# -gt 2 ]; then
    echo 1>&2 "usage: $0 <webtest> <port>"
    exit 2
fi

#查看程序是否在运行如果在运行则kill掉相应的进程,并重新启动程序
ps_out=`ps -ef | grep $1 | grep -v 'grep' | grep -v $0`
result=$(echo $ps_out | grep "$1")
if [[ "$result" != "" ]];then
    echo "webtest is running"
    echo "kill webtest..."
    killall -e webtest
    #创建log文件记录输出
    rm log
    touch log
    #$1 和 $2分别表示参数1和参数2, 讲输出从新定位到log,因为这里将程序跑在后台,
    #并且将屏蔽掉SIGHUP信号,防止shell终端关闭的时候程序也跟着关闭
    nohup ./$1 $2 > log 2>&1 &
    echo "restart $1 port: $2"
else
    echo "webtest is not running"
    rm log
    touch log
    nohup ./$1 $2 > log 2>&1 &
    echo "start $1 port: $2"
fi

写了一个改进版的,保留原来版本不删除,主要是为了进行对面思路,前面的思路,和改进后的思路,
到底改进了哪里
改进后shell代码如下:

#!/bin/bash
if [ $# -lt 2 ]; then
    echo 1>&2 "usage: $0 < webtest > < port >"
    exit 2
elif [ $# -gt 2 ]; then
    echo 1>&2 "usage: $0 < webtest > < port >"
    exit 2
fi

if [ -e $1_log ]
then
    echo "$1_log exist"
else
    echo "create $1_log..."
    touch $1_log
fi

ps_out=`ps -ef | grep $1 | grep -v 'grep' | grep -v $0`
result=$(echo $ps_out | grep "$1")
if [[ "$result" != "" ]];then
    echo "$1 is running"
    echo "kill webtest..."
    killall -e webtest
    nohup ./$1 $2 > $1_log 2>&1 &
    echo "restart $1 port: $2"
else
    echo "$1 is not running"
    nohup ./$1 $2 > $1_log 2>&1 &
    echo "start $1 port: $2"
fi

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值