“output to stdout”是什么意思?

3

我是一位新手,想学习bash编程。我不确定什么是“输出到标准输出(stdout)”。这是否意味着将内容打印到命令行?

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

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

它将一个字符串输出到终端。这是否意味着它正在“输出到标准输出(stdout)”?

谢谢

3个回答

3

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

  • stdin (0)
  • stdout (1)
  • stderr (2)

通常,这些文件描述符中的每一个都将指向启动进程的终端。例如:

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

然而,Bash允许使用输入/输出重定向来修改这种行为:

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的标准输出不再是终端,而grep的输出是当前终端。如果您想将grep的输出重定向到文件中,可以使用以下命令:
wget -q  http://192.168.0.1/test -O -  | grep -m 1 'Hello' > output.txt

那么在我的特定示例中,输出被定向到终端,这种情况下是标准输出(stdout)? - 0xSina

3

是的,stdout就是终端(除非使用>运算符将其重定向到文件中或使用|将其输入到另一个进程的stdin中)。

在您的特定示例中,您实际上是通过| grep ...通过grep然后重定向到终端。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接