2

Opening 3 jobs in ash with i.e.

sh & sh & sh &

and counting this jobs with i.e.

jobs -p | wc -l

shows

3

which is OK. But trying to assign this job count to a variable with

JOBNR=$(jobs -p | wc -l)

and printing this variable with

echo $JOBNR

shows

0

Why? Maybe during the assignment a new Shell (without jobs) was opened? What could be the best solution?

Thanks in advance.

deetee
  • 65
  • 7

2 Answers2

1

Yes, it's a matter of how the shell implements the command substitution. In bash, JOBNR gets the value 3, but in dash, 0.

chepner
  • 389,128
  • 51
  • 403
  • 529
  • A similar assignment seems to work:VAR=$(ls | wc -l) provides with echo $VAR the number of files (16). – deetee Feb 12 '16 at 15:43
  • Those are external commands; `jobs` is a shell-builtin, so which shell actually executes it determines what its output is. – chepner Feb 12 '16 at 15:45
  • Could it be possible to pipe or stream the output to a variable? Storing the output to a file with `jobs -p | wc -l > tempfile` and a following `read VAR < tempfile` works fine but involving a file is not an optimal solution. – deetee Feb 13 '16 at 15:44
  • That suffers from the same problem in `dash`; `jobs -p` is run in a subshell induced by the pipe, and outputs 0. – chepner Feb 13 '16 at 16:27
0

Finally I found a solution for my problem - doing it by stages and with attention to quotes: JOBNR=$(jobs -p); JOBNR=$(echo "$JOBNR" | wc -w); echo $JOBNR does the job.

The first expression does the raw job and stores a list (with some lines) in JOBNR.

Echoing $JOBNR (with quotes (!) because of more than one line stored in JOBNR) and counting the words with wc could be (re)assigned to JOBNR the "regular" way (VAR=$(command)).

deetee
  • 65
  • 7