8

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

./command.sh < myfile

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

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

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

4

3 回答 3

4

只需使用cat命令将文件与标准输入合并:

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

或者

cat myfile - | ./command.sh

cat命令

cat代表连接_ _

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.
...

(请阅读精细手册;-) _ _ _

你可以写

cat file1 file2 file3 ... fileN

cat file1 - file2

cat - file1

cat file1 -

根据你的需要...

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

我用于head -c -1heredoc删除尾随换行符。command 确实逐行模拟任何命令处理: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]
于 2012-12-30T01:12:04.943 回答
2

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

inputer.sh

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

Usage

sh inputer.sh input_file | sh your-script.sh
于 2012-12-29T23:32:15.247 回答
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

于 2012-12-29T23:19:04.773 回答