Search code examples
shellposixvariable-assignmentjobsash

Assign job count number to variable (POSIX-Shell)


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.


Solution

  • 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)).