目录
- 一. 简介
- 二. 常见用法
- 2.1 输出重定向
- 2.2 错误重定向
- 2.3 同时重定向标准输出 + 错误
- 2.4 输入重定向
- 2.5 特殊设备
- 三. 这样设计的好处
- 3.1 区分正常信息和错误信息
- 3.2 方便调用方脚本处理
- 3.3 与管道结合时更清晰
- 四. 案例
一. 简介
⏹在 Linux/Unix 中,一切都是文件(文件、目录、设备、管道、网络套接字等)。
当进程打开一个文件(或设备、socket 等),内核会返回一个 整数编号 来代表它,这个编号就是 FD
。
※File Descriptor
(文件描述符)的简写。
进程之后对这个文件的所有操作(读、写、关闭等)都是通过FD
文件描述符来完成的。
FD | 名称 | 说明 | 默认指向 |
---|
0 | stdin | 标准输入 | 键盘 |
1 | stdout | 标准输出 | 终端屏幕 |
2 | stderr | 标准错误 | 终端屏幕 |
二. 常见用法
2.1 输出重定向
写法 | 含义 |
---|
command > file | 把 标准输出写入文件,覆盖 |
command >> file | 把 标准输出追加到文件 |
command 1> file | 等同于 > file ,指定 stdout |
2.2 错误重定向
写法 | 含义 |
---|
command 2> file | 把 标准错误写入文件 |
command 2>> file | 把 标准错误追加到文件 |
command 2>&1 | 把 stderr 重定向到 stdout 的位置 |
2.3 同时重定向标准输出 + 错误
写法 | 含义 |
---|
command > file 2>&1 | stdout 和 stderr 都写入 file |
command &> file | Bash专用简写,stdout+stderr 一起写入 file |
command &>> file | stdout+stderr 一起追加到 file |
2.4 输入重定向
写法 | 含义 |
---|
command < file | 把文件作为标准输入 |
command 0< file | 等同于 < file |
2.5 特殊设备
写法 | 含义 |
---|
>/dev/null | 丢弃 stdout |
2>/dev/null | 丢弃 stderr |
&>/dev/null | 丢弃 stdout + stderr(Bash常用,不兼容sh) |
💥>/dev/null 2>&1 | 丢弃 stdout + stderr(兼容所有shell) |
三. 这样设计的好处
3.1 区分正常信息和错误信息
stdout
通常表示程序的正常结果(比如命令执行的输出)。stderr
用来提示警告、错误、用户输入异常等情况。
echo "正常结果"
echo "出错了!" >&2
3.2 方便调用方脚本处理
- 上层脚本或调用者可以分别捕获 stdout 和 stderr。
./myscript.sh >output.log 2>error.log
3.3 与管道结合时更清晰
- 管道
|
只会传递 stdout
,stderr
会被分开。 - 如果
command1
里错误信息走 stderr
,它就不会影响后面的数据处理逻辑。
command1 | command2
四. 案例
4.1 if判断
⏹判断指定的环境变量是否存在
>/dev/null 2>&1
:用于将printenv USERNAME
的标准输出和错误全部丢弃
if printenv USERNAME >/dev/null 2>&1; thenecho "环境变量 USERNAME 存在"
elseecho "环境变量 USERNAME 不存在"
fi
if printenv USERNAME &>/dev/null; thenecho "环境变量 USERNAME 存在"
elseecho "环境变量 USERNAME 不存在"
fi
⏹判断指定的命令是否存在
if ! command -v keytool >/dev/null 2>&1; thenecho "【keytool】命令并没有被安装, 请确认!"exit 1
fi
4.2 ls查询
- 有2个文件夹,其中
0915
的文件夹只有root用户才能读取其中的文件 - 直接
ls -l 09*
查看时,会提示权限不足 2>/dev/null
将标准错误丢弃之后,屏幕上不会显示错误提示
apluser@FengYeHong-HP:work$ ls -ld 09*
drwx------ 2 root root 4096 Sep 15 18:58 0915
drwxr-xr-x 2 apluser apluser 4096 Sep 15 19:00 0915_01
apluser@FengYeHong-HP:work$
apluser@FengYeHong-HP:work$ ls -l 09*
ls: cannot open directory '0915': Permission denied
0915_01:
total 0
apluser@FengYeHong-HP:work$
apluser@FengYeHong-HP:work$ ls -l 09* 2>/dev/null
0915_01:
total 0
ls 09* >out.txt 2>err.txt
:stdout 到 out.txt,stderr 到 err.txt
apluser@FengYeHong-HP:work$ ls 09*
ls: cannot open directory '0915': Permission denied
0915_01:
apluser@FengYeHong-HP:work$
apluser@FengYeHong-HP:work$ ls 09* >out.txt 2>err.txt
apluser@FengYeHong-HP:work$
apluser@FengYeHong-HP:work$ cat out.txt
0915_01:
apluser@FengYeHong-HP:work$
apluser@FengYeHong-HP:work$ cat err.txt
ls: cannot open directory '0915': Permission denied
ls 09* >all_info.txt 2>&1
:stdout 和 stderr 都输出到 all.txt
apluser@FengYeHong-HP:work$ ls 09* >all_info.txt 2>&1
apluser@FengYeHong-HP:work$
apluser@FengYeHong-HP:work$ cat all_info.txt
ls: cannot open directory '0915': Permission denied
0915_01: