bug-bash
[Top][All Lists]
Advanced

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

Re: simple prob?


From: Greg Wooledge
Subject: Re: simple prob?
Date: Tue, 29 Jun 2021 16:35:28 -0400

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.

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 name.

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]