Comment 2 for bug 243406

Revision history for this message
JM Williams (jmdwilliams) wrote :

I think that the problem here is that Dash is running “jobs | wc -l” and
“jobs | cat” in subshells. These subshells have no stopped jobs or running
background jobs to report, which is why the output of jobs is empty.

If in Dash you run:

    sleep 10 &
    jobs

you will get the output you are expecting from jobs, but if you run:

    sleep 10 &
    (jobs)

(which puts jobs in a subshell), you will get no output.

The Single Unix Specification states,¹ “Additionally, each command of a
multi-command pipeline is in a subshell environment; as an extension, however,
any or all commands in a pipeline may be executed in the current environment.”
This shows that merely putting jobs into a pipeline *could* cause it to be in
a subshell.

The Dash man page states, “Note that unlike some other shells, each process in
the pipeline is a child of the invoking shell (unless it is a shell builtin,
in which case it executes in the current shell -- but any effect it has on the
environment is wiped).” As jobs is a shell builtin (so says “type jobs”), it
ought to execute in the current shell, and so shouldn’t it report stopped and
background jobs of the shell containing the pipeline? I’m not sure, so I’m
going to leave this bug open for someone else to decide.

However, if you want to make your shell script POSIX-compliant and therefore
portable, then you presumably shouldn’t rely on the behaviour that you were
expecting. I don’t know what the best workaround here would be, but *one*
workaround would be to use “>”-redirection to write from jobs to a temporary
file which you could then grep and line-count: this alone wouldn’t create a
multi-command pipeline.

In any case, I wouldn’t expect Bash in its default mode necessarily to behave
the same as Dash, which aims to be POSIX compliant. Bash when started with
the option --posix I *might* expect to behave the same as Dash. In this case,
it doesn’t, however: Bash gives the same output if you change the first line
of your Bash script to “#!/bin/bash --posix”.

I hope some of the above helps!

    1. http://www.opengroup.org/onlinepubs/000095399/utilities/xcu_chap02.html#tag_02_12