How to read mutliline input from stdin into variable and how to print one out in shell(sh,bash)?


Question

What I want to do is the following:

  1. read in multiple line input from stdin into variable A
  2. make various operations on A
  3. pipe A without losing delimiter symbols (\n,\r,\t,etc) to another command

The current problem is that, I can't read it in with read command, because it stops reading at newline.

I can read stdin with cat, like this:

my_var=`cat /dev/stdin`

, but then I don't know how to print it. So that the newline, tab, and other delimiters are still there.

My sample script looks like this:

#!/usr/local/bin/bash

A=`cat /dev/stdin`

if [ ${#A} -eq 0 ]; then
        exit 0
else
        cat ${A} | /usr/local/sbin/nextcommand
fi
1
55
2/1/2013 7:32:50 AM

Accepted Answer

This is working for me:

myvar=`cat`

echo "$myvar"

The quotes around $myvar are important.

63
5/1/2017 9:15:53 AM

In Bash, there's an alternative way; man bash mentions:

The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

$ myVar=$(</dev/stdin)
hello
this is test
$ echo "$myVar"
hello
this is test

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon