管道(Pipe)是Linux/Unix系统中一种强大的功能,它允许将一个命令的输出直接作为另一个命令的输入。管道使用竖线符号|
表示。
command1 | command2 | command3 ...
# 查看/etc/passwd文件并筛选出包含"bash"的行
cat /etc/passwd | grep bash
# 统计当前目录下文件数量
ls | wc -l
# 查看所有运行的进程并筛选出nginx相关进程
ps aux | grep nginx
# 查看占用CPU最高的进程
ps aux | sort -nk 3 | tail
# 查看最近10条系统日志并筛选出错误信息
journalctl -n 10 | grep -i error
# 统计日志中不同错误出现的次数
cat /var/log/syslog | grep -i error | sort | uniq -c | sort -nr
# 查看文件内容并高亮关键词
cat file.txt | grep --color=auto "keyword"
# 对文件内容排序并去重
cat file.txt | sort | uniq
tee命令 - 同时输出到文件和屏幕
command1 | tee file.txt | command2
xargs - 将输入转换为命令行参数
find . -name "*.log" | xargs rm
命名管道(FIFO) - 创建持久化的管道
mkfifo mypipe
command1 > mypipe & command2 < mypipe
进程替换 - 将命令输出作为文件处理
diff <(command1) <(command2)
管道是Linux命令行高效工作的核心概念之一,熟练掌握管道可以极大提高工作效率。