Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda functions in bash

Tags:

bash

lambda

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

$ someCommand | xargs -L1 (lambda function) 
like image 562
Daniel Avatar asked Jan 15 '09 19:01

Daniel


People also ask

Can you use Bash with Lambda?

AWS recently announced the "Lambda Runtime API and Lambda Layers", two new features that enable developers to build custom runtimes. So, it's now possibile to directly run even bash scripts in Lambda without hacks.

What does [- Z $1 mean in Bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What is lambda function with example?

Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression).

Are there functions in Bash?

There are two ways to implement Bash functions: Inside a shell script, where the function definition must be before any calls on the function. Alongside other bash alias commands and directly in the terminal as a command.


1 Answers

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.

like image 176
j_random_hacker Avatar answered Sep 17 '22 10:09

j_random_hacker