lambda functions in bash

What about this?

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

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


if you want true functions, and not just pipes or while loops (e.g. if you want to pass them around, as if they were data) I’d just not do lambdas, and define dummy functions with a recurring dummy name, to use right away, and throw away afterwards. Like so:

# An example map function, to use in the example below.
map() { local f="$1"; shift; for i in "$@"; do "$f" "$i"; done; }

# Lambda function [λ], passed to the map function.
λ(){ echo "Lambda sees $1"; }; map λ *

Like in proper functional languages, there’s no need to pass parameters, as you can wrap them in a closure:

# Let’s say you have a function with three parameters
# that you want to use as a lambda:
# (As in: Partial function application.)
trio(){ echo "$1 Lambda sees $3 $2"; }

# And there are two values that you want to use to parametrize a
# function that shall be your lambda.
pre="<<<"
post=">>>"

# Then you’d just wrap them in a closure, and be done with it:
λ(){ trio "$pre" "$post" "$@"; }; map λ *

I’d argue that it’s even shorter than all other solutions presented here.


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.

[EDIT 26/7/2016]

According to commenter Evi1M4chine, setting $IFS to the empty string before running read X (e.g., with the command IFS='' read X) should also preserve spaces at the beginning and end when storing the result into $X, meaning you aren't forced to use $REPLY.

Tags:

Lambda

Bash