1

I am trying to store stdin into a variable in a pipeline:

$ echo 'message' | variable="-" ; echo $variable

I know I can do a script for this; but I am just trying this way to understand.

Any idea why this isn't working?

Jahid
  • 21,542
  • 10
  • 90
  • 108
Jikku Jose
  • 18,306
  • 11
  • 41
  • 61

1 Answers1

1

You can do this:

echo 'message' | ( var="$(< /dev/stdin)"; echo "$var" )

Or:

echo 'message' | { var="$(< /dev/stdin)"; echo $var; }

Note: ( ... ) opens another new subshell after pipe.


Another way (using lastpipe bash>=4.2):
set +m;shopt -s lastpipe  # set +m disables job control
echo "hello world" | read test; echo test=$test
echo "hello world" | test="$(</dev/stdin)"; echo test=$test

Bash Manual says:

lastpipe

If set, and job control is not active, the shell runs the last command of a pipeline not executed in the background in the current shell environment.

Note that, job control is turned off by default in non-interactive shell.

Jahid
  • 21,542
  • 10
  • 90
  • 108
  • pipe will open a new subshell anyways. unless `shopt -s lastpipe` is set. this is new after 4.2 though. – Jason Hu Jul 09 '15 at 16:55
  • @HuStmpHrrr yap, pipe opens one and `( )` another, but `{ }` doesn't open another. Nothing is changed though (in this case) – Jahid Jul 09 '15 at 17:04