将文件内容放在stdin上而不发送eof

问题描述 投票:0回答:3

将文件内容放入标准输入的典型方法如下:

./command.sh < myfile

这会将 myfile 的所有内容放在 stdin 上,然后也发送 eof。我想将内容放在 stdin 上而不添加 EOF。

对于各种交互程序,我希望以一系列命令开始程序,然后继续与程序交互。如果未发送 eof,程序将等待更多输入,然后我可以交互式输入。

这在 bash 中可能吗?我当前的解决方案是将内容扔到剪贴板上,然后粘贴它们。有更好的方法吗?

bash
3个回答
7
投票

使用 cat 命令简单地将文件与

stdin
合并:

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

cat myfile - | ./command.sh

注:

-
代表STDIN。您可以使用
/dev/stdin
代替:

cat myfile /dev/stdin | ./command.sh

cat
命令

cat
代表 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.
...

(请Read The Fine M年度;-)

你可以写

cat file1 file2 file3 ... fileN

以及

cat file1 - file2

cat - file1

cat file1 -

取决于您的需要...

复杂示例,使用 heredocherestring 而不是文件

我使用

head -c -1
drop尾随newlineheredoc中。
sed
命令确实模拟任何命令处理逐行

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')

应输出:

[Here is some text, followed by an empty line]
[]
[Then a string, on THIS line: Hello world]

2
投票

解决方案是使用

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

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

并喂养

fifo

echo foobar > /tmp/fifo

停止“听”:

echo break > /tmp/fifo

参见

man mkfifo


2
投票

另一种方法是使用另一个脚本来提供输入:

inputer.sh

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

Usage

sh inputer.sh input_file | sh your-script.sh
© www.soinside.com 2019 - 2024. All rights reserved.