'Put file contents on stdin without sending eof
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?
Solution 1:[1]
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]
Solution 2:[2]
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
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 |
