The role is to redirect the output of the results of the command to the specified file.
Redirect command list is as follows:
File descriptors 0 typically standard input (STDIN), . 1 is a standard output (STDOUT), 2 is the standard error output (STDERR).
1, output redirection
Redirect output to file Example:
Note that, in any file1 already existing content will be replaced with new content, change the file1, redirected again:
If you want to add new content to the end of the file, use >> operator:
2, input redirection
Note: The above example of two different results: the first example, the file name is output; the second is not, since it only knows the content read from stdin.
Redirect the input and output can be used simultaneously:
Under normal circumstances, each Unix / Linux command is running will open three files:
- Standard input file (stdin): stdin file descriptor is 0, Unix default program data read from stdin.
- Standard output file (stdout): stdout file descriptor 1, Unix program default data output to stdout.
- The standard error file (stderr): stderr file descriptor 2, Unix program writes error information to stderr stream.
By default, command> file redirect stdout to the file, command <file to redirect stdin to file.
If you want to redirect stderr to file, you can write:
$ command 2> file
If you want to append to the end of file stderr file, you can write:
$ command 2>> file
scenes to be used:
在项目中,经常需要查看日志文件的错误信息,来进行排查问题,也就是说,我们需要解决如何把错误信息保存到文件中,而不是默认显示在显示器上。
示例1:(只重定向错误)
为什么说如上只是重定向错误呢,为了证明,列出一个已存在加不存在的文件
可见只有nofile文件的错误信息保存到了nginx.log文件中。
如果希望将 stdout 和 stderr 合并后重定向到 file,可以这样写:
$ command > file 2>&1
或者
$ command &> file
示例:
注意一个细节,nodfile的错误输出在hello.txt之前,这是因为shell自动赋予了错误消息更高的优先级。
如果希望将 stdout 和 stderr 分别重定向到不同的file,可以这样写:
$ command 2>file1 1>file2
示例:
3、/dev/null 文件
如果希望执行某个命令,但又不希望在屏幕上显示输出结果,可以将输出重定向到 /dev/null:
$ command > /dev/null
/dev/null 是一个特殊的文件,写入到它的内容都会被丢弃;如果尝试从该文件读取内容,那么什么也读不到。但是 /dev/null 文件非常有用,将命令的输出重定向到它,会起到"禁止输出"的效果。使用>&2
如果希望屏蔽 stdout 和 stderr,可以这样写:
$ command > /dev/null 2>&1
4、临时重定向
使用符号: >&2
如果以如下方式执行,则两句都会输出
如果执行的时候又进行了错误重定向,则正常输出一句到显示器,错误日志则写入错误文件中,达到了分离的效果。
5、永久重定向(exec)
脚本中,exec将STDERR输出重定向到error.log,所以执行This is the start of the script正常语句将输出到显示器,
接下来,把STDOUT重定向输出到access.log中,所以This output should go to the access.log会显示到access.log文件中,
但你仍然可以将echo语句输出发给STDERR,所以but this should go to the error.log最终会写入到error.log。
运行结果如下: