This is working for me:
myvar=`cat`
echo "$myvar"
The quotes around $myvar
are important.
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
tee does the job
#!/bin/bash
myVar=$(tee)
This assignment will hang indefinitely if there is nothing in the pipe...
var="$(< /dev/stdin)"
We can prevent this though by doing a timeout read
for the first character. If it times out, the return code will be greater than 128 and we'll know the STDIN pipe (a.k.a /dev/stdin
) is empty.
Otherwise, we get the rest of STDIN by...
IFS
to NULL for just the read
command-r
-d ''
.Thus...
__=""
_stdin=""
read -N1 -t1 __ && {
(( $? <= 128 )) && {
IFS= read -rd '' _stdin
_stdin="$__$_stdin"
}
}
This technique avoids using var="$(command ...)"
Command Substitution which, by design, will always strip off any trailing newlines.
If Command Substitution is preferred, to preserve trailing newlines we can append one or more delimiter characters to the output inside the $()
and then strip them off outside.
For example ( note $(parens)
in first command and ${braces}
in second )...
_stdin="$(awk '{print}; END {print "|||"}' /dev/stdin)"
_stdin="${_stdin%|||}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With