ToolkitX
知识库工具箱

输入输出与重定向

stdin, stdout, stderr, 管道

15min·入门

01. 标准输入输出

每个进程有三个标准文件描述符:0 标准输入,1 标准输出,2 标准错误。
bash
# 重定向输出
echo "hello" > file.txt       # 覆盖写入
echo "world" >> file.txt      # 追加写入

# 重定向错误
command 2> error.log
command > output.log 2>&1
command &> all.log

# Here Document
cat << EOF
第一行
第二行
EOF

# read 读取输入
read -p "请输入姓名: " NAME
read -s -p "请输入密码: " PASSWORD

02. 管道与过滤器

管道 | 将一个命令的输出作为另一个命令的输入。这是 Unix 哲学的核心。
bash
# 基本管道
echo "hello world" | tr '[:lower:]' '[:upper:]'

# 常用组合
cat access.log | awk '{print $1}' | sort | uniq -c | sort -rn | head -10

# tee 同时输出到屏幕和文件
command | tee output.log

知识测验

1/5正确 0

2>&1 的作用是什么?

下一节

正则与文本处理

下一节