Skip to content

管道

基本用法

简单管道

bash
#!/bin/bash

# 使用管道连接命令
ls -l | grep ".txt"

多个管道

bash
#!/bin/bash

# 使用多个管道连接命令
ls -l | grep ".txt" | wc -l

管道原理

子shell

bash
#!/bin/bash

# 管道在子shell中执行
count=0
echo "1" | count=$(cat)
echo $count  # 输出:0

变量传递

bash
#!/bin/bash

# 使用管道传递变量
name="张三"
echo "$name" | while read line; do
    echo "收到: $line"
done

实用示例

示例1:文件统计

bash
#!/bin/bash

# 统计文件数量
count=$(ls -l | grep "^-" | wc -l)
echo "文件数量: $count"

# 统计目录数量
count=$(ls -l | grep "^d" | wc -l)
echo "目录数量: $count"

示例2:日志分析

bash
#!/bin/bash

# 统计错误日志
count=$(grep "ERROR" app.log | wc -l)
echo "错误数量: $count"

# 查找特定错误
grep "ERROR" app.log | grep "connection"

示例3:数据处理

bash
#!/bin/bash

# 处理数据
cat data.txt | grep "pattern" | sort | uniq

示例4:进程监控

bash
#!/bin/bash

# 查找特定进程
ps aux | grep "nginx" | grep -v "grep"

最佳实践

1. 使用管道

bash
# 好的做法
ls -l | grep ".txt"

# 不好的做法
ls -l > temp.txt
grep ".txt" temp.txt
rm temp.txt

2. 避免子shell问题

bash
# 好的做法
while read line; do
    echo "$line"
done < input.txt

# 不好的做法
cat input.txt | while read line; do
    echo "$line"
done

3. 使用管道链

bash
# 好的做法
command1 | command2 | command3 | command4

# 不好的做法
command1 > temp1.txt
command2 < temp1.txt > temp2.txt
command3 < temp2.txt > temp3.txt
command4 < temp3.txt

总结

管道的关键点:

  1. 基本用法:使用 | 连接命令
  2. 管道原理:在子shell中执行
  3. 变量传递:使用管道传递数据
  4. 实用示例:文件统计、日志分析、数据处理、进程监控
  5. 最佳实践:使用管道、避免子shell问题、使用管道链

下一节我们将学习 grep 命令的使用。