将文件内容放入标准输入的典型方法如下:
./command.sh < myfile
这会将 myfile 的所有内容放在 stdin 上,然后也发送 eof。我想将内容放在 stdin 上而不添加 EOF。
对于各种交互程序,我希望以一系列命令开始程序,然后继续与程序交互。如果未发送 eof,程序将等待更多输入,然后我可以交互式输入。
这在 bash 中可能吗?我当前的解决方案是将内容扔到剪贴板上,然后粘贴它们。有更好的方法吗?
使用 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 -
取决于您的需要...
我使用
head -c -1
来drop尾随newline在heredoc中。 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]
解决方案是使用 fifo。
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
另一种方法是使用另一个脚本来提供输入:
inputer.sh
:cat $1
while read line; do
echo $line
done
Usage
:sh inputer.sh input_file | sh your-script.sh