如何在 Bash 中一起使用 watch 和 jobs 命令?

dab*_*st1 9 linux bash watch

如何将watch命令与jobs命令一起使用,以便我可以监视后台作业何时完成?

我按如下方式执行它,但我没有从作业中获得输出:

watch jobs
Run Code Online (Sandbox Code Playgroud)

如果我自己运行作业,我的测试后台作业会得到以下结果:

jobs
[1]+  Running                 nohup cat /dev/random >/dev/null &
Run Code Online (Sandbox Code Playgroud)

Fra*_*ran 14

watch命令记录如下:

SYNOPSIS
   watch  [-dhvt]  [-n  <seconds>] [--differences[=cumulative]] [--help]
          [--interval=<sec-onds>] [--no-title] [--version] <command>
[...]
NOTE
   Note that command is given to "sh -c" which means that you may need to
   use extra quoting to get the desired effect.
Run Code Online (Sandbox Code Playgroud)

关于给出命令的部分sh -c意味着jobs您正在运行的命令正在watch与生成作业的会话不同的 shell 会话中运行,因此无法看到其他 shell。问题从根本上说jobs是一个内置的 shell,必须在生成您想要查看的作业的 shell 中运行。

您可以获得的最接近的是在产生作业的 shell 中使用 while 循环:

$ while true; do jobs; sleep 10; done
Run Code Online (Sandbox Code Playgroud)

您可以在 shell 启动脚本中定义一个函数以使其更易于使用:

myjobwatch() { while true; do jobs; sleep 5; done; }
Run Code Online (Sandbox Code Playgroud)

然后你只需要输入myjobwatch.

  • 我添加了一个“清除”。`N=1; 虽然是真的;做工作;睡眠 ${N}; 清除; 完成;` (2认同)