What I want to do is the following:
- read in multiple line input from
stdin
into variableA
- make various operations on
A
- 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
This is working for me:
The quotes around
$myvar
are important.tee does the job
[updated]
This assignment will hang indefinitely if there is nothing in the pipe...
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 theread
command-r
-d ''
.Thus...
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 )...If you do care about preserving trailing newlines at the end of the output, use this:
This uses the trick from here.
Yes it works for me too. Thanks.
is the same as
Well yes. From the
bash
man page:In Bash, there's an alternative way;
man bash
mentions: