help-bash
[Top][All Lists]
Advanced

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

Re: name of a global variable to store the result of a function


From: João Eiras
Subject: Re: name of a global variable to store the result of a function
Date: Sun, 24 May 2020 19:39:26 +0200

Use whatever variable name you want.
But if you want to make utility code that robust and does not depend on
magic variable names, you could pass the name of the output variable as a
parameter, e.g.:

function do_stuff {
  local varname="$1"
  local result="somevalue"
  eval "$varname=\"\$result\""
}

myresult=
do_stuff myresult
echo r:$myresult




On Sun, 24 May 2020 at 01:26, Peng Yu <address@hidden> wrote:

> As shown in the runtime comparison below, I'd like to return values
> via a global variable instead via printing to stdout and $() in
> certain situations.
>
> Is there a well-accepted convention for the global variable to store the
> result?
>
> $ cat ./main2.sh
> #!/usr/bin/env bash
> # vim: set noexpandtab tabstop=2:
>
> function f {
>     echo 42
> }
>
> function g {
>     result=42
> }
>
> TIMEFORMAT=%R
> time for ((i=0;i<3000;++i)); do
>     x=$(f)
> done
>
> time for ((i=0;i<3000;++i)); do
>     g
>     x=$result
> done
> $ ./main2.sh
> 4.181
> 0.048
>
> --
> Regards,
> Peng
>
>


reply via email to

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