Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read full stdin until EOF when stdin comes from `cat` bash

Tags:

bash

stdin

cat

I'm trying to read full stdin into a variable :

script.sh

#/bin/bash

input=""
while read line
do
  echo "$line"
  input="$input""\n""$line"
done < /dev/stdin



echo "$input" > /tmp/test

When I run ls | ./script.sh or mostly any other commands, it works fine.

However It doesn't work when I run cat | ./script.sh , enter my message, and then hit Ctrl-C to exit cat.

Any ideas ?

like image 390
edi9999 Avatar asked Aug 19 '15 09:08

edi9999


People also ask

How do you read stdin until EOF?

Use the sys. stdin. readlines() method to read user input until EOF. The readlines() method will return a list containing the lines.

How does cat << EOF work in bash?

This type of redirection instructs the shell to read input from the current source until a line containing only word (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input for a command.

What does cat << EOF mean?

This operator stands for the end of the file. This means that wherever a compiler or an interpreter encounters this operator, it will receive an indication that the file it was reading has ended.

How do you echo EOF?

Show activity on this post. There is no way to echo out an EOF. An EOF can only be generated either by reaching the end of a file or by invoking the keypress bound to the eof terminal setting ( Ctrl D by default) when the file being read is bound to the terminal.


1 Answers

I would stick to the one-liner

input=$(cat)

Of course, Ctrl-D should be used to signal end-of-file.

like image 120
Roberto Reale Avatar answered Sep 21 '22 17:09

Roberto Reale