简体   繁体   English

将 `jobs -p` 的输出捕获到变量中

[英]Capture output of `jobs -p` into variable

I am using shell trying to capture list of background jobs:我正在使用shell尝试捕获后台作业列表:

sleep 11 | tee log_1.txt &
sleep 12 | tee log_2.txt &

jobs -p # this returns PIDs

X=$(jobs -p)
echo ${X}

Then I start it like this: sh ./script.sh然后我这样开始: sh ./script.sh

But for some reason I get nothing.但由于某种原因,我什么也没得到。

Trying to debug it I see that jobs -p actually returns the list of items.尝试调试它时,我看到jobs -p实际上返回了项目列表。

Something like X=$(ls -al) also works as expected and the content is captured.X=$(ls -al)这样的东西也可以按预期工作并且内容被捕获。

Your code works fine in bash : 您的代码可以在bash正常工作:

$ bash myfile
10715
10717
10715 10717
$

But it does fail in dash , which is probably what your sh is: 但是它的确不会在dash中失败,这可能是您的sh是什么:

$ dash myfile
11048
11046

$

(see Why does my bash code fail when I run it with sh? ). (请参见为什么在使用sh运行bash代码时,我的bash代码失败? )。

dash is within its rights to behave this way (and Bash is arguably wrong) because POSIX specifies that "The jobs utility shall display the status of jobs that were started in the current shell environment", and you have created a new shell environment through your use of the subshelling $(...) . dash有权这样做(Bash可能是错误的),因为POSIX指定 “作业实用程序应显示在当前Shell环境中启动的作业的状态”,并且您已经通过自己的方式创建了新的Shell环境使用subshel​​ling $(...)

If you want to do it in a sh compatible way you can redirect to a temp file and read that instead. 如果要以与sh兼容的方式进行操作,则可以重定向到临时文件并读取该文件。 Alternatively, you can collect the pids of each started background job using $! 另外,您可以使用$!收集每个已启动的后台作业的PID $! .

In subshells, jobs -p will print only the active jobs.在子 shell 中, jobs -p将仅打印活动作业。 This means that:这意味着:

true &
sleep 2 &
sleep 1
jobs=$(jobs -p)

will only capture the second job (since the first one will be finished).只会捕获第二个作业(因为第一个作业将完成)。

To capture all jobs, including jobs finished but not waited for (zombies), do this:要捕获所有作业,包括已完成但未等待(僵尸)的作业,请执行以下操作:

# all jobs, simple variable
read jobs < <(jobs -p)

# all jobs, array variable
readarray -t jobs < <(jobs -p)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM