在Linux系统中,错误输出重定向是一种将命令执行产生的错误信息(标准错误,stderr)重定向到指定位置的技术,而不是默认显示在终端上。
Linux中有三种标准I/O流: 1. 标准输入(stdin) - 文件描述符0 2. 标准输出(stdout) - 文件描述符1 3. 标准错误(stderr) - 文件描述符2
错误输出重定向主要操作的是文件描述符2(stderr)。
command 2> error.log
这会将命令的错误信息写入error.log文件,而不会显示在终端上。
command 2>> error.log
与上面类似,但会追加内容而不是覆盖原有文件。
command > output.log 2> error.log
标准输出写入output.log,错误输出写入error.log。
command > combined.log 2>&1
# 或者更简洁的写法
command &> combined.log
command 2> /dev/null
command 2> /dev/null | another_command
command 2>&1 | another_command
(command > output.log) >& error.log
find / -name "*.conf" 2> /dev/null
gcc program.c -o program 2> compile_errors.txt
./script.sh &> script_output.log
command 2> error.log && mail -s "Command Errors" user@example.com < error.log
理解错误输出重定向对于Linux系统管理和脚本编写非常重要,它能帮助你更好地控制程序的输出和错误处理。