如何通过 shell 脚本中的管道读取命令的输出?
我有一个命令,例如
cat file | sh myscript.sh
如何将 cat file
的输出读入 myscript.sh?
I have a command like
cat file | sh myscript.sh
How do i read the output of cat file
into myscript.sh?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
详细信息取决于您的数据的性质和您的意图。
既然您已经说过您希望将整个文件放在一个变量中,那么它就是
The details depend on the nature of your data and your intentions.
Now that you've said you want the whole file in a single variable, it's
您可以不使用
cat
,只需将文件传递给您的脚本吗:Can you not use
cat
, just pass the file to your script:我使用类似的方法:
这样,如果将一个或多个文件名作为参数给出,它们将被传递到<我的命令>。如果没有给出文件,
cat
会检索标准输入并将其传递给 <我的命令>。I use something like:
That way, if one or more file names are given as arguments, they are passed to <my commands>. If no file is given,
cat
retrieves the standard input and passes it to <my commands>.仅当您的输入不包含任何
NUL
(\0
) 字符时,此方法才有效 - 变量不能包含NUL
,因为它用于设置变量的末尾。现在您可以使用
$REPLY
变量,它将包含文件的所有内容。This only works if your input does not contain any
NUL
(\0
) characters - Variables can't containNUL
because it's used to set the end of the variable.Now you can use the
$REPLY
variable, which will contain all the contents of the file.如果您必须使用此 --
cat file | sh myscript.sh
-- 将文件传输到另一个 shell 脚本的方向,使用 xargs:file.txt
的内容:myscript.sh
的内容:使用< code>xargs 来实现以下任一功能:
变体 0:
来自 xargs 手册页:
变体 1:
变体 2:
变体 3:
请注意,
-I
受到每行最大字符数限制。可以通过指定--max-chars
或-s
来设置此限制,如下所示:If you must use this --
cat file | sh myscript.sh
-- orientation of piping a file to another shell script, use xargs:Content of
file.txt
:Content of
myscript.sh
:Use
xargs
to achieve either of the following:Variation 0:
From xargs man page:
Variation 1:
Variation 2:
Variation 3:
Mind you,
-I
is limited by maximum character limit per line. This limit can be set by specifying--max-chars
or-s
as following:目前的许多答案似乎都在鼓励OP读取脚本中的文件,而不是回答问题。如果您正在调用命令:
并且希望将文件的内容存储在变量中,则只需让脚本将 stdin 读入变量即可。最简单的方法是使用 cat:
请注意,原始命令是 UUOC,可以通过以下方式完成:
或
另请注意,将 stdin 读入变量 v 将一直读取,直到 stdin 关闭,因此如果您调用 myscript.sh直接(即,在 tty 上使用 stdin),它将阻塞,直到用户点击 ^d(或平台上指示 EOF 的任何键序列)。将文件名作为参数传递给脚本确实是一个更好的主意。
It seems like a lot of the current answers are encouraging the OP to read the file in the script, rather than answering the question. If you are invoking the command:
and you want the contents of file in a variable, then you simply need to have the script read stdin into a variable. The easiest way to do that is with cat:
Note that the original command is a UUOC, and could be done with:
or
Also note that reading stdin into the variable v will read until stdin is closed, so that if you invoke myscript.sh directly (ie, with stdin on a tty), it will block until the user hits ^d (or whatever key sequence indicates EOF on the platform.) It really is a better idea to pass the filename as an argument to the script.