Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put file contents on stdin without sending eof

Tags:

bash

The typical way of putting a file's contents on stdin is as follows:

./command.sh < myfile

This puts all the contents of myfile on stdin and then sends the eof as well. I want to put the contents on stdin without adding the EOF.

For various interactive programs, I wish to begin the program with a sequence of commands, but then continue to interact with the program. If the eof is not sent, the program would wait for more input, which I could then type interactively.

Is this possible in bash? My current solution is to throw the contents on the clipboard and then just paste them. Is there a better way of doing this?

like image 774
matzahboy Avatar asked Dec 29 '12 23:12

matzahboy


3 Answers

Simply merge file with stdin by using cat command:

./command.sh < <(cat myfile -)

or

cat myfile - | ./command.sh

cat command

cat stand for concatenate:

man cat
NAME
       cat - concatenate files and print on the standard output

SYNOPSIS
       cat [OPTION]... [FILE]...

DESCRIPTION
       Concatenate FILE(s), or standard input, to standard output.
...

(please Read The Fine Manual ;-)

You could write

cat file1 file2 file3 ... fileN

as well as

cat file1 - file2

cat - file1

cat file1 -

depending on your need...

Complex sample, using heredoc and herestring instead of files

I use head -c -1 in order to drop trailing newline in heredoc. sed command does simulate any command proccessing line by line:

sed 's/.*/[&]/' < <(cat <(head -c -1 <<eof 
Here is some text, followed by an empty line

Then a string, on THIS line: 
eof
) - <<<'Hello world')

Should output:

[Here is some text, followed by an empty line]
[]
[Then a string, on THIS line: Hello world]
like image 182
F. Hauri Avatar answered Oct 22 '22 11:10

F. Hauri


A solution for this is using a fifo.

test -p /tmp/fifo || mkfifo /tmp/fifo

while true; do
    read line < /tmp/fifo
    echo "$line"
    [[ $line == break ]] && $line
done

and to feed the fifo :

echo foobar > /tmp/fifo

to stop "listening" :

echo break > /tmp/fifo

See man mkfifo

like image 40
Gilles Quenot Avatar answered Oct 22 '22 11:10

Gilles Quenot


Another way is to use another script to give your input:

inputer.sh:

cat $1
while read line; do
  echo $line
done

Usage:

sh inputer.sh input_file | sh your-script.sh
like image 40
perreal Avatar answered Oct 22 '22 10:10

perreal