Bash 到 运行 一个独立循环的脚本,该循环顺序启动后台进程

Bash script to run a detached loop that sequentially starts backgound processes

我正在尝试 运行 在我通过 ssh 连接到的远程 Linux 服务器上进行一系列测试。

这是我尝试过的:

#!/usr/bin/env bash
# Assembling a list of commands to be executed sequentially
TESTRUNS="";
for i in `ls ../testSet/*`;
do 
  MSG="running test problem ${i##*/}";
  RUN="mySequentialCommand $i > results/${i##*/} 2> /dev/null;";
  TESTRUNS=$TESTRUNS"echo $MSG; $RUN"; 
done
#run commands with nohup to be able to log out of ssh session
nohup eval $TESTRUNS &

但看起来 nohup 与 eval 的配合不太好。 有什么想法吗?

nohup 如果您希望您的脚本 运行 甚至 关闭 shell 之后,则需要

nohup。所以是的。

并且 &RUN 中不是必需的,因为您使用 &.

执行命令

现在您的脚本在 for 循环中构建命令,但不执行它。这意味着您将只有最后一个文件 运行ning。如果要 运行 所有文件,则需要在循环中执行 nohup 命令。但是 - 你不能 运行 带有 & 的命令,因为这将 运行 命令在后台和 return 到脚本,它将执行循环中的下一个项目.最终这将 运行 所有文件并行。

nohup eval $TESTRUNS 移动到 for 循环中,但同样,您不能 运行 它与 &。您需要做的是 run the script itself with nohup,即使在 shell 关闭后,脚本也会在后台一次循环遍历所有文件。

您可以看一下 screen,它是具有附加功能的 nohup 的替代品。我会将您的测试脚本替换为 while [ 1 ]; do printf "."; sleep 5; done 以测试 screen 解决方案。
命令 screen -ls 是可选的,只是显示正在发生的事情。

prompt> screen -ls
No Sockets found in /var/run/uscreens/S-notroot.
prompt> screen
prompt> screen -ls
prompt> while [ 1 ]; do printf "."; sleep 5; done
# You don't get a prompt. Use "CTRL-a d" to detach from your current screen
prompt> screen -ls
# do some work
# connect to screen with batch running
prompt> screen -r
# Press ^C to terminate the batch (script printing dots)
prompt> screen -ls
prompt> exit
prompt> screen -ls

Google screenrc 查看如何自定义界面。

您可以将脚本更改为

#!/usr/bin/env bash
# Assembling a list of commands to be executed sequentially
for i in ../testSet/*; do
do 
  echo "Running test problem ${i##*/}"
  mySequentialCommand $i > results/${i##*/} 2> /dev/null 
done

当你不使用 screen 或屏幕内简单的 scriptname 时,上面的脚本可以用 nohup scriptname & 启动。