2013-04-10 98 views
3

bash编程的新手。我不确定'输出到标准输出'是什么意思。这是否意味着打印到命令行?'输出到stdout'是什么意思

如果我有一个简单的bash脚本:

#!/bin/bash 
wget -q http://192.168.0.1/test -O - | grep -m 1 'Hello' 

其输出字符串到终端。这是否意味着它'输出到标准输出'?

感谢

回答

2

Linux系统(以及大多数其他)上的每个进程至少有3个开放文件描述符:

  • 标准输入(0)
  • 标准输出(1)
  • stderr的(2)

Regualary每此文件描述符将指向到t他从终点开始。就像这样:

cat file.txt # all file descriptors are pointing to the terminal where you type the  command 

然而,bash允许使用input/output redirection修改此行为:

cat < file.txt # will use file.txt as stdin 

cat file.txt > output.txt # redirects stdout to a file (will not appear on terminal anymore) 

cat file.txt 2> /dev/null # redirects stderr to /dev/null (will not appear on terminal anymore 

同样是当您使用管道符号像发生的事情:

wget -q http://192.168.0.1/test -O - | grep -m 1 'Hello' 

是什么实际发生的情况是wget进程的标准输出(| |之前的进程)被重定向到grep进程的标准输入。所以wget的stdout不再是终端,而grep的输出是当前终端。如果你想重定向的grep的输出,例如一个文件,然后使用此:

wget -q http://192.168.0.1/test -O - | grep -m 1 'Hello' > output.txt 
+0

所以在我的特定示例中,输出被定向到终端,在这种情况下是标准输出? – 0xSina 2013-04-10 23:41:44

+0

有更新一点。希望这可以让事情更清楚。 – hek2mgl 2013-04-10 23:43:47

3

是,stdout是终端(除非它重定向到使用>操作一个文件或到使用|另一个进程的标准输入)

在你的具体的例子,你实际上重定向然后通过grep使用| grep ...到终端。