Shell 输入/输出重定向
三个文件描述符、>/>>/2>&1、here-document 与管道。
Key Points0 是输入、1 是输出、2 是错误;2>&1 要写在 > 后面,顺序反了错误还是进终端。
三个描述符
| FD | Name | Default |
|---|---|---|
| 0 | stdin | Keyboard |
| 1 | stdout | Terminal |
| 2 | stderr | Terminal |
输出重定向
Bash
echo "to file" > /tmp/out.txt
cat /tmp/out.txt
echo "append" >> /tmp/out.txt
cat /tmp/out.txtOutput
to file
to file
append合并错误输出
Bash
ls /nope > /tmp/e.log 2>&1
echo "exit=$?"
wc -l < /tmp/e.logOutput
exit=2
1> file 2>&1 means: point stdout at file, then point stderr wherever stdout now points. Writing 2>&1 > file leaves stderr on the terminal.
丢弃输出
Bash
ls /nope 2>/dev/null || echo "silenced"Output
silenced输入重定向与 here-document
Bash
printf 'a\nb\nc\n' > lines.txt
wc -l < lines.txt
USER_NAME="alice"
APP_DIR="/opt/app"
cat <<EOF
name=$USER_NAME
dir=$APP_DIR
EOFOutput
3
name=alice
dir=/opt/app<<EOF expands variables; <<'EOF' does not. Use the quoted form when the template must keep literal $, such as nginx variables.管道与 tee
Bash
printf 'b\na\nc\n' | sort | head -2
printf 'x\n' | tee /tmp/t.txt > /dev/null
cat /tmp/t.txtOutput
a
b
xtee writes to a file and stdout at once — handy for logging while watching. set -o pipefail makes $? reflect any stage failing.
三个描述符
| 描述符 | 名称 | 默认 |
|---|---|---|
| 0 | 标准输入 | 键盘 |
| 1 | 标准输出 | 终端 |
| 2 | 标准错误 | 终端 |
输出重定向
Bash
echo "to file" > /tmp/out.txt
cat /tmp/out.txt
echo "append" >> /tmp/out.txt
cat /tmp/out.txtOutput
to file
to file
append合并错误输出
Bash
ls /nope > /tmp/e.log 2>&1
echo "exit=$?"
wc -l < /tmp/e.logOutput
exit=2
1> file 2>&1 的正确含义是:先把 stdout 指向 file,再把 stderr 指向「stdout 当前指向的地方」。写成 2>&1 > file 时,stderr 还指向终端,错误信息照样打到屏幕上。
丢弃输出
Bash
ls /nope 2>/dev/null || echo "silenced"Output
silenced输入重定向与 here-document
Bash
printf 'a\nb\nc\n' > lines.txt
wc -l < lines.txt
USER_NAME="alice"
APP_DIR="/opt/app"
cat <<EOF
name=$USER_NAME
dir=$APP_DIR
EOFOutput
3
name=alice
dir=/opt/app<<EOF 会展开变量,<<'EOF' 不会。写配置模板时如果想保留 $ 字面量(比如 nginx 变量),必须给 EOF 加引号。管道与 tee
Bash
printf 'b\na\nc\n' | sort | head -2
printf 'x\n' | tee /tmp/t.txt > /dev/null
cat /tmp/t.txtOutput
a
b
xtee 一边写文件一边往 stdout 输出,适合既想留日志又想看屏幕的场景;set -o pipefail 让管道中任一环失败都能被 $? 捕获。