Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a bash function, how do I get stdin into a variable

Tags:

linux

bash

shell

I want to call a function with a pipe, and read all of stdin into a variable.

I read that the correct way to do that is with read, or maybe read -r or read -a. However, I had a lot of problems in practise doing that (esp with multi-line strings).

In the end I settled on

function example () {
  local input=$(cat)
  ...
}

What is the idiomatic way to do this?

like image 369
Paul Biggar Avatar asked Sep 02 '15 22:09

Paul Biggar


People also ask

What is bash stdin?

stdin: Stands for standard input. It takes text as input. stdout: Stands for standard output. The text output of a command is stored in the stdout stream.

Can bash functions return values?

A bash function can return a value via its exit status after execution. By default, a function returns the exit code from the last executed command inside the function. It will stop the function execution once it is called. You can use the return builtin command to return an arbitrary number instead.

What is $_ in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.


1 Answers

input=$(cat) is a perfectly fine way to capture standard input if you really need to. One caveat is that command substitutions strip all trailing newlines, so if you want to make sure to capture those as well, you need to ensure that something aside from the newline(s) is read last.

input=$(cat; echo x)
input=${input%x}   # Strip the trailing x

Another option in bash 4 or later is to use the readarray command, which will populate an array with each line of standard input, one line per element, which you can then join back into a single variable if desired.

readarray foo
printf -v foo "%s" "${foo[@]}"
like image 88
chepner Avatar answered Sep 29 '22 06:09

chepner