Pipe assigns variable

You could do something like this, if you use bash:

echo cart | while read spo; do echo $spo; done

Unfortunately, variable "spo" won't exist outside of the while-do-done loop. If you can get what you want done inside the while-loop, that will work.

You can actually do almost exactly what you wrote above in ATT ksh (not in pdksh or mksh) or in the fabulous zsh:

% echo cart | read spo
% echo $spo
cart

So, another solution would be to use ksh or zsh.


echo cart | { IFS= read -r spo; printf '%s\n' "$spo"; }

Would work (store the output of echo without the trailing newline character into the spo variable) as long as echo outputs only one line.

You could always do:

assign() {
  eval "$1=\$(cat; echo .); $1=\${$1%.}"
}
assign spo < <(echo cart)

The following solutions would work in bash scripts, but not at the bash prompt:

shopt -s lastpipe
echo cat | assign spo

Or:

shopt -s lastpipe
whatever | IFS= read -rd '' spo

To store the output of whatever up to the first NUL characters (bash variables can't store NUL characters anyway) in $spo.

Or:

shopt -s lastpipe
whatever | readarray -t spo

to store the output of whatever in the $spo array (one line per array element).


If I understand the issue correctly you want to pipe stdout to a variable. At least that was what I was looking for and ended up here. So for those who share my fate:

spa=$(echo cart)

Assigns cart to the variable $spa.

Tags:

Bash

Variable