Shell 输入/输出重定向

三个文件描述符、>/>>/2>&1、here-document 与管道。

Beginner
Key Points0 是输入、1 是输出、2 是错误;2>&1 要写在 > 后面,顺序反了错误还是进终端。

三个描述符

FDNameDefault
0stdinKeyboard
1stdoutTerminal
2stderrTerminal

输出重定向

Bash
echo "to file" > /tmp/out.txt
cat /tmp/out.txt
echo "append" >> /tmp/out.txt
cat /tmp/out.txt
Output
to file
to file
append

合并错误输出

Bash
ls /nope > /tmp/e.log 2>&1
echo "exit=$?"
wc -l < /tmp/e.log
Output
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
EOF
Output
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.txt
Output
a
b
x

tee writes to a file and stdout at once — handy for logging while watching. set -o pipefail makes $? reflect any stage failing.

Friends & Partners