On Tue, 29 Jun 2021 16:35:28 -0400 Greg Wooledge <g...@wooledge.org> wrote:
> On Tue, Jun 29, 2021 at 01:21:44PM -0700, L A Walsh wrote: > > I hope a basic question isn't too offtopic. > > More of a help-bash question, in my opinion, but close enough. > > > Say I have some number of jobs running: > > > > > jobs|wc -l > > 3 > > OK. > > > Would like to pass a varname to njobs to store the answer in, like: > > > njobs n > > echo "$n" > > 3 > > "How do I pass a value back from a function to its caller, you know, > like a function in any other programming language can do" is one of the > holy grails of shell programming. There is no sane answer. You appear > to be going down the "pass a variable name by reference" path, so: > > unicorn:~$ jobs | wc -l > 3 > unicorn:~$ njobs() { local _n=$(jobs | wc -l); eval "$1=\$_n"; } > unicorn:~$ njobs walsh > unicorn:~$ echo "$walsh" > 3 > > Now you just need to add sanity-checking on the argument of njobs, to > avoid whatever code injection the malicious caller wants to perform. I can't fathom the switch to eval there. Why not printf -v "$1" %s "$_n", for example? It even rejects invalid identifiers. -- Kerin Millar