且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

bash stdout重定向在for循环中

更新时间:2023-02-03 12:59:12

启动 my_tool 时,该工具中通常有3个文件描述符:

When you start my_tool, there are normally 3 file-descriptors available in the tool:

  • STDIN
  • STDOUT
  • STDERR

STDIN用于输入,因此与该问题无关.STDOUT用于标准输出.这是文件描述符1.如果您这样做

STDIN is used for input, and therefore irrelevant for this question. STDOUT is used for standard output. This is file-descriptor 1. If you do

ls 1> /dev/null

ls的STDOUT写入/dev/null .如果您未添加 1 ,如 ls>/dev/null ,假设您的意思是STDOUT.

the STDOUT of ls is written to /dev/null. If you do not add the 1, as in ls > /dev/null, it is assumed that you mean STDOUT.

STDERR用作错误消息的标准输出.STDERR的数量为2.

STDERR is used as standard output for error messages, in the broadest sense of the word. The number of STDERR is 2.

使用 ls 代替您的 my_command ls>文件会将列表放在文件中. ls/non_existing_dir_>文件会将 ls 的STDOUT放在 file 中.但是STDOUT上没有输出,并且由于STDERR没有重定向,它将被发送到终端.

Using ls instead of your my_command, ls > file will put the listing in the file. ls /non_existing_dir_ > file will put the STDOUT of ls in the file. But there is no output on STDOUT, and because STDERR is not redirected, it will be send to the terminal.

总而言之,

ls . /non_existing_dir 2>stderr >stdout

将把.的目录列表放在stdout文件中,stderr中不存在目录的错误.

will put the directory listing of . in the file stdout and the error for the non-existing directory in stderr.

使用 2>& 1 ,您可以将filedescriptor2(STDERR)的输出重定向到文件描述符1(SDTOUT).

With 2>&1 you redirect the output of filedescriptor2 (STDERR) to file descriptor 1 (SDTOUT).

要使事情复杂一点,可以添加其他文件描述符编号.例如:

To complicate things a bit, you can add other file descriptor numbers. For example:

exec 3>file

会将文件描述符3(新创建的)的输出放在 file 中.还有

will put the output of file descriptor 3 (which is newly created) in file. And

ls 1>&3

然后将文件描述符1的输出重定向到文件描述符3,将 ls 的输出有效地放置在 file 中.

will then redirect the output of file descriptor 1 to file descriptor 3, effectively putting the output of ls in file.