如何通过shell脚本中的管道读取命令的输出?

时间:2011-11-29 11:26:29

标签: shell

我有一个像

这样的命令
cat file | sh myscript.sh

如何将cat file的输出读入myscript.sh?

6 个答案:

答案 0 :(得分:3)

cat file | while read something; do echo "This is $something" ; done

详细信息取决于数据的性质和您的意图。

既然你已经说过要将整个文件放在一个变量中,那就是

var="$(cat file)"

答案 1 :(得分:0)

您是否可以使用cat,只需将文件传递给您的脚本:

myscript.sh file

答案 2 :(得分:0)

我用的是:

#!/bin/sh

cat "$@" | <my commands>

这样,如果一个或多个文件名作为参数给出,它们将被传递给&lt; my commands&gt;。如果没有给出文件,cat将检索标准输入并将其传递给&lt; my commands&gt;。

答案 3 :(得分:0)

仅当您的输入不包含任何NUL\0)字符时才有效 - 变量不能包含NUL,因为它用于设置变量的结尾。

read -r -d ''

现在您可以使用$REPLY变量,该变量将包含文件的所有内容。

答案 4 :(得分:0)

如果你必须使用这个 - cat file | sh myscript.sh - 将文件管道到另一个shell脚本的方向,请使用xargs

内容file.txt

blah1
blah2
blah3

内容myscript.sh

#!/bin/bash
echo $1

使用xargs来实现以下任一目标:

变化0:

user@host:~$ cat file.txt | xargs -E ./myscript.sh
blah1 blah2 blah3

来自xargs man page

-E eof-str
  Set the end of file string to eof-str.  If the end of 
  file string occurs as a  line of  input,  the rest of 
  the input is ignored.  If neither -E nor -e is used, 
  no end of file string is used.

变体1:

user@host:~$ cat file.txt | xargs ./myscript.sh 
blah1

变体2:

user@host:~$ cat file.txt | xargs --null ./myscript.sh 
blah1 blah2 blah3

变体3:

user@host:~$ cat file.txt | xargs -I{} ./myscript.sh {}
blah1
blah2
blah3

请注意,-I受限于每行的最大字符数限制。可以通过指定--max-chars-s来设置此限制:

user@host:~$ cat file.txt | xargs -I{} -s 100000 ./myscript.sh {}
blah1
blah2
blah3

答案 5 :(得分:0)

似乎很多当前的答案都鼓励OP在脚本中读取文件,而不是回答问题。如果您正在调用命令:

$ cat file | sh myscript.sh

并且您希望文件的内容在变量中,然后您只需要让脚本将stdin读入变量。最简单的方法是使用cat:

#!/bin/sh

v=$(cat)

请注意,原始命令是UUOC,可以通过以下方式完成:

$ < file sh myscript.sh

$ sh myscript.sh < file

另请注意,将stdin读入变量v将读取直到stdin关闭,因此如果直接调用myscript.sh(即,使用tdin上的stdin),它将阻塞,直到用户点击^ d(或者其他键序列表示平台上的EOF。)将文件名作为参数传递给脚本确实是一个更好的主意。

相关问题