jobsn=( $( jobs -p ) ) jobsn=${jobsn[@]} On Fri, Jul 2, 2021, 09:10 Phi Debian <phi.deb...@gmail.com> wrote:
> On Tue, Jun 29, 2021 at 10:23 PM L A Walsh <b...@tlinx.org> wrote: > > > I hope a basic question isn't too offtopic. > > Say I have some number of jobs running: > > > > > jobs|wc -l > > 3 > > --- > > > > Would like to pass a varname to njobs to store the answer in, like: > > > > So I can run: > > > > > njobs n > > echo "$n" > > 3 > > > > > This a a double question 'how to', and I see no bash bugs here. > > The 2 questions are > - how do I pass a variable name as an output argument to a function ('n' in > your 'jobs n' example) > - how to set a variable in a sub command? that is no doable, a sub command > can't return variable to its parent, so you obviously have to do things > diffrently. > > A simple 2 liners, solve all this, with no code injection blah.... > > > PW$ jobs > [1] Running sleep 11111111111 & > [2] Running sleep 11111111111 & > [3]- Running sleep 11111111111 & > [4]+ Running sleep 11111111111 & > > PW$ > > PW$ function njobs > > { [ "$1" != "n" ] && typeset -n n="$1" > > typeset -a t ; readarray t <<<"$(jobs)" ;n=${#t[@]} > > } > > PW$ njobs n ; echo $n > 4 > > # explanations (you may skip here) > #=========================== > [ "$1" != "n" ] && typeset -n n="$1" > This make sure the given output variable name is a valid SHELL identifier, > providing anything not valid in "$1" will break there. > This also enforce that the given $1 output variable name doesn't match our > own local nameref name, if it match we don't do our nameref, and re-use the > upper scope output variable name, that by definition is a valid variable > name if we got that far. > > typeset -a t > define a local array that we will fill, being local mean the booking is > done at function return > > readarray t <<<"$(jobs)" ; > Fill the array with your command you want to count lines for. > > n=${#t[@]} > Fill the output variable > > All is safe, all is clean, no 'apparent' temp file, no sub command :) > > Shell programing is fun :) >