30

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

$ someCommand | xargs -L1 (lambda function)

7 Answers 7

26

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.

6
  • 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
    Jan 29, 2009 at 19:58
  • 1
    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 Jul 9, 2009 at 1:17
  • 2
    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. Jul 9, 2009 at 5:02
  • 1
    The only reason external spaces are stripped, is because they are field separators. If you disable that, by setting IFS='', you aren’t forced to use $REPLY. :) Jul 25, 2016 at 19:47
  • 1
    @Evi1M4chine: Thanks! I've updated the answer. If it's not quite right, feel free to edit :) Jul 26, 2016 at 9:34
13

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.

9
  • Can you define a function from inside another function's body? Because that's what lambda is about
    – pqnet
    Aug 19, 2014 at 5:09
  • 1
    @pqnet: The main difference to a normal function, is that lambdas are anonymous and defined inline. Which makes them convenient to use as parameters and generally in expressions. Many languages allow defining functions in functions in a way that they aren’t lambdas. I don’t think bash allows defining functions in-line, nor anonymously. But it definitely allows passing them as parameters, even into the closure of the passed-to function, and making their names just about anonymous. So while my reply is necessarily indeed not a full lambda, it’s as close as you gonna get. Jul 25, 2016 at 19:24
  • For a question tackling actually passing anonymous code, see: unix.stackexchange.com/questions/81202/… It’s a mess though. :) Jul 25, 2016 at 19:39
  • @pqnet: Updated answer: It is not what lambda in about. Is originates from lambda calculus. But yes, in bash, you can define funtions in other functions. But they will be available globally, unless you manually unset them at the end of the surrounding function, which is quite the hazard and unexpected for a scripting language. Dec 25, 2021 at 4:59
  • What I meant to say in 2014 is likely that the general understanding when you say "this language has lambdas" is that the language supports some syntax to declare anonymous functions, usually in the expression scope. I agree that the reference is to "lambda calculus" where all functions are anonymous.
    – pqnet
    Dec 25, 2021 at 11:53
4

What about this?

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

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

3
#!/bin/bash

function customFunction() {
    eval $1
}

command='echo Hello World; echo Welcome;'
customFunction "$command"

GL

Source

1

if you want only xargs (due parallel -P N option for example), and only bash as function code, then bash -c can be used as parameter for xargs.

seq 1 10 | tr '\n' '\0' | xargs -0 -n 1 bash -c 'echo any bash code $0'

tr and -0 option are used here to disable any xargs parameters substitutions.

1

Yes. One can pass around a string variable representing a command call, and then execute the command with eval.

Example:

command='echo howdy'
eval "$command"
1

The eval trick has been already mentioned but here's my extended example of bash closures:

#!/usr/bin/env bash

set -e

function multiplyBy() {
    X="$1"

    cat <<-EOF
        Y="\$1"
        echo "$X * \$Y = \$(( $X * \$Y ))"
    EOF
}

function callFunc() {
    CODE="$1"
    shift

    eval "$CODE"
}

MULT_BY_2=`multiplyBy 2`
MULT_BY_4=`multiplyBy 4`

callFunc "$MULT_BY_2" 10
callFunc "$MULT_BY_4" 10

PS I've just came up with this for a completely different purpose and was just searching google to see if sb is using that. I actually needed to evaluate a reusable function in the context (shell) of main script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.