在 shell 脚本中终止并重新启动 ngrok

kst*_*ich 5 shell sh ngrok

我需要ngrok每 24 小时终止并重新启动我的服务器,所以我考虑使用 cronjob 来运行 shell 脚本。我面临的问题是,当我ngrok在 shell 脚本中重新启动时,它会在给定的 shell 会话中启动它。

我如何才能ngrok在不同的会话中启动,以便我可以继续在同一脚本中进行其他检查?

到目前为止我的代码:

# grabs the PID for the current running ngrok
ngrok_pid=$(pgrep ngrok)
echo "Current ngrok PID = ${ngrok_pid}"

# kills ngrok
kill_ngrok_pid=$(kill -9 $ngrok_pid)

# get exit status code for last command
check=$?

# check if the exit status returned success
if [ $check -eq 0 ]; then
    # re-start ngrok
    $(./ngrok http 5000 &)
    # do more checks below...
else
    echo "NO ngrok PID found"
fi
Run Code Online (Sandbox Code Playgroud)

tri*_*eee 0

如果我能够猜测您想问什么,请在子进程中运行新命令。你已经在这样做了,尽管很笨拙。

\n
#!/bin/sh\n\nngrok_pid=$(pgrep ngrok)\necho "$0: Current ngrok PID = ${ngrok_pid}" >&2\n\nif [ "$ngrok_pid" ] && kill -9 $ngrok_pid\nthen\n    ( ./ngrok http 5000 & )\n    # do more checks below...\nelse\n    echo "$0: NO ngrok PID found" >&2\nfi\n
Run Code Online (Sandbox Code Playgroud)\n

这避免了测试 \xe2\x80\x9c$?\xe2\x80\x9d 以查看命令是否成功以及多余的命令替换。避免在没有 PID 的情况下if [ "$ngrok_pid" ] &&尝试运行。kill最后,我们小心地将脚本的名称包含在其诊断消息中,并将其打印到标准错误>&2而不是标准输出。

\n

ngrok更好的解决方案可能是作为服务运行,并且仅用于cron告诉服务重新启动;但具体如何做到这一点取决于系统。幸运的是,该文档包含针对多种流行架构的说明。然后,您所需要的一切cron工作中所需要的就是

\n
ngrok service restart\n
Run Code Online (Sandbox Code Playgroud)\n

原始服务应该在重新启动或类似的情况下启动

\n
ngrok service install --config /etc/ngrok.yml\n
Run Code Online (Sandbox Code Playgroud)\n

但我按照ngrok手册了解详细信息。

\n