tags:

views:

360

answers:

2

Is there a way to implement/use lambda functions in bash? I'm thinking of something like:

$ someCommand | xargs -L1 (lambda function)
+6  A: 

I don't know of a way to do this, however you may be able to accomplish what you're trying to do using:

somecommand | while read -r; do echo "Something with $REPLY"; done

This will also be faster, as you won't be creating a new process for each line of text.

[EDIT 2009-07-09] I've made two changes:

  1. Incorporated litb's suggestion of using -r to disable backslash processing -- this means that backslashes in the input will be passed through unchanged.
  2. Instead of supplying a variable name (such as X) as a parameter to read, we let read assign to its default variable, REPLY. This has the pleasant side-effect of preserving leading and trailing spaces, which are stripped otherwise (even though internal spaces are preserved).

From my observations, together these changes preserve everything except literal NUL (ASCII 0) characters on each input line.

j_random_hacker
+1, that's awesome!
orip
I guess the issue I've had in the past with this method is that it works great for strings that have no spaces. If, say, the output of <somecommand> is a list of files, some of which have spaces, "read X" fails. I have read somewhere how to deal with that, but never seem to recall the specifics.
Daniel
I feel your pain... In fact "read X" *almost* does the right thing -- it does preserve any internal spaces, but if a line begins or ends with spaces, these will be removed. BTW the OP's xargs command splits on internal spaces (and even concatenate lines *ending* in spaces because of "-L1"!)
j_random_hacker
the OP's original command also fails on filenames such as *foo's garden*, treating the `'` quoting specially. BTW i recommend using `read -r` instead of plain `read`. This will preserve quotes. Like it will read *A\B\C* correctly. Btw nice answer, +1
Johannes Schaub - litb
Good point litb. Some more testing reveals that using the default variable, REPLY, instead of a named variable such as X, enables leading and trailing spaces to be preserved, and with your -r switch even backslashes will be preserved. I'll update the main answer.
j_random_hacker
A: 

What about this?

somecommand | xargs -d"\n" -I{} echo "the argument is: {}"

(assumes each argument is a line, otherwise change delimiter)