[Top][All Lists]

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

Re: [Help-bash] Closure concept in bash

From: Peng Yu
Subject: Re: [Help-bash] Closure concept in bash
Date: Tue, 31 Jan 2012 09:25:54 -0600

> How very bizarre.  I still don't quite understand the purpose, but I'll
> set it aside for now.

Because you don't quite understand the benefit of closure, you have
the following question.

The benefit of closure can be understood at least from the perspective
of refactoring. For example, you have a piece of refactored code that
uses many variables (say 10). Now you want to encapsulate it into a
function because you want to iterate through one of the variable.
Without closure, and you don't not want to pass the other 9 arguments
as arguments to the function (also in my case the 9 arguments are read
from the command line, for example by getopt, so you can not set it in
the function), you will have to rely on global variables. But
everybody knows the short coming of global variables. So you end up
with an unsafe function.

With closure, you don't not need to specify the 9 arguments to the
function, it also makes the function safe.

Essentially, you are saying pass everything in the function arguments,
which is not convenient. It could simpler so that you don't have to
pass all the 9 arguments, if there were a closure concept in bash.

> Once again, what are you trying to do here?  Are you trying to launch
> 5 jobs at a time out of a list of 1000 jobs, where each "job" is a
> bash function, and therefore is not available to GNU parallel, which
> is an external program?
> The obvious way to do that would be to put the function's defining code
> in a file, and then source it in a shell created by GNU parallel.
> $ cat myfunc
> myfunc() {
>  echo "\$1 is $1"
> }
> $ parallel bash -c 'source ./myfunc; myfunc "$1"' _ -- 1 2 3
> $1 is 2
> $1 is 1
> $1 is 3
> This is much cleaner and safer than trying to export a function through
> the environment and simply hoping that it magically comes through.


reply via email to

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