[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: simple prob?

From: L A Walsh
Subject: Re: simple prob?
Date: Tue, 29 Jun 2021 14:05:46 -0700
User-agent: Thunderbird (Windows/20100228)

On 2021/06/29 13:35, Greg Wooledge wrote:
unicorn:~$ njobs() { local _n=$(jobs | wc -l); eval "$1=\$_n"; }
   ARG...I thought about that and rejected it because I
thought the "jobs|wc-l" would be in a sub-shell and not pickup
the background jobs!  Double arg, this works as well:
sjobs() { local j;read j< <(jobs|wc -l); printf ${1:+-v $1} "%s\n" "$j"; }

About the only thing that doesn't work are variations on
jobs|wc-l|read n -- since if read is in current process jobs doesn't
pick up the children, but if jobs is in current process, then read
isn't, and 'n' is lost.

Of course I was focusing on -s/-u lastpipe to provide some variation
but that was the only variation that would seem to be guaranteed not
to work.  Oi!
Now you just need to add sanity-checking on the argument of njobs, to
avoid whatever code injection the malicious caller wants to perform.
   That would be 'me', so I'm going to rule out malicious
code injection! :-), but that's also why I used printf to
write the output, the worst that could happen is some varname
is overwritten with the answer, no?

And maybe consider adding "make sure $1 isn't _n" to the list of your
sanity checks, since the caller can't be permitted to use that particular
variable namhe.
Simpler -- don't use a variable:

  njobs() { printf ${1:+-v $1} "%s\n" "$(jobs |wc -l)"; }

The use of the builtin expansion off of the parameter has the side
benefit of printing the answer to output if no var is given.

So...hmmm...how is it that jobs picks up the right answer in what
would seem to be a subshell?  Special cased?

unicorn:~$ njobs _n
unicorn:~$ echo "$_n"

(At least it didn't go into an infinite loop!)

reply via email to

[Prev in Thread] Current Thread [Next in Thread]