如何在后台运行脚本(linux openwrt)



我有这个脚本:

#!/bin/sh
while [ true ] ; do
    urlfile=$( ls /root/wget/wget-download-link.txt | head -n 1 )
    dir=$( cat /root/wget/wget-dir.txt )
    if [ "$urlfile" = "" ] ; then
        sleep 30
        continue
    fi
    url=$( head -n 1 $urlfile )
    if [ "$url" = "" ] ; then
        mv $urlfile $urlfile.invalid
        continue
    fi
    mv $urlfile $urlfile.busy
    wget -b $url -P $dir -o /www/wget.log -c -t 100 -nc
    mv $urlfile.busy $urlfile.done
done

该脚本基本上每 30 秒检查一次 wget-download-link.txt 的任何新 URL,如果有新 URL,它将使用 wget 下载它,问题是当我尝试像这样在 Putty 上运行此脚本时

/root/wget/wget_download.sh --daemon

它仍然在前台运行,我仍然可以看到终端输出。如何让它在后台运行?

在 OpenWRT(2023 年之前)中,默认情况下既没有可用的nohup也没有可用的screen,因此只有内置命令的解决方案是启动一个带括号的子外壳,并将该子外壳放在背景中,&

(/root/wget/wget_download.sh >/dev/null 2>&1 )&

您可以在桌面上轻松测试此结构,例如使用

(notify-send one && sleep 15 && notify-send two)&

。然后在这 15 秒结束之前关闭控制台,您将看到括号中的命令在关闭控制台后继续执行。

以下命令也将起作用:

((/root/wget/wget_download.sh)&)&

这样,您就不必在用于OpenWrt的路由器的紧凑内存空间中安装"nohub"命令。

几年前我在某个地方发现了这个。它有效。

脚本

末尾的&应该足够了,如果您看到脚本的输出,则表示stdout和/或stderr未关闭,或未重定向到/dev/null

你可以用这个答案:

如何将所有输出重定向到/dev/null

我正在使用 openwrt merlin,让它工作的唯一方法是使用 crud cron 管理器[1]。Nohub和屏幕不能作为解决方案。

cru a pinggw "0 * * * */bin/ping -c 10 -q 192.168.2.254"

像魅力一样的作品

[

1][https://www.cyberciti.biz/faq/how-to-add-cron-job-on-asuswrt-merlin-wifi-router/]

https://openwrt.org/packages/pkgdata/coreutils-nohup

opkg update
opkg install coreutils-nohup
nohup yourscript.sh &
您可以使用

nohup .

nohup yourscript.sh

nohup yourscript.sh &

即使您关闭腻子会话,您的脚本也会继续运行,并且所有输出都将写入同一目录中的文本文件。

Nohup 通常与 nice 命令结合使用,以较低的优先级运行进程。

nohup nice yourscript.sh &

请参阅:http://en.wikipedia.org/wiki/Nohup

对于 Openwrt Merlin 系统中的 busybox,我得到了一个更好的解决方案,它结合了 cru 和日期命令

cru a YOUR_UNIQUE_CRON_NAME "`date -D '%s' +'%M %H %d %m *' -d $(( `date +%s`+2*60 ))` YOUR_CMD_HERE"

这将添加一个 cron 作业在 2 分钟后运行,并且只运行一次。

灵感来自PlagTag的想法。

以另一种方式,这些代码将尝试:

ssh admin@192.168.1.1 "/jffs/your_script.sh &"

简单,没有任何程序,如nohup屏幕...
(顺便说一句:在华硕-梅林固件上工作)

试试这个:

 nohup /root/wget/wget_download.sh >/dev/null 2>&1 &

它将进入后台,因此当您关闭 Putty 会话时,它仍将运行,并且不会向终端发送消息。

最新更新