Featured image of post Web 开发人员必备的 Linux 命令和管道Featured image of post Web 开发人员必备的 Linux 命令和管道

Web 开发人员必备的 Linux 命令和管道

掌握基本的 Linux shell 命令和管道来搜索日志 (grep/find)、检查服务器资源 (htop/df) 以及自动执行终端任务。

介绍

无论您从事前端还是后端工作,shell 命令熟练程度对于 Web 开发人员来说都是一项重要技能。

命令行任务不断出现:sshing 到 AWS/VPS 实例、在 Docker 容器内调试或编写自动化 CI/CD 管道 shell 脚本(例如 GitHub Actions)。

本文介绍了基本的 Linux 命令,并解释了如何使用 管道 (|) 将它们链接在一起,以解决服务器问题并解析日志文件。


1. 搜索文件并解析日志

当服务器崩溃或行为异常时,您必须能够快速搜索大量文本文件以定位错误。

① grep(文本搜索)

在文件内容中搜索与指定字符串或模式匹配的行。

# Search for the word "fatal" in error.log, ignoring case distinctions (-i)
grep -i "fatal" /var/log/nginx/error.log

# Search recursively (-r) for the string "API_KEY" in the current directory
grep -r "API_KEY" ./src/

②find(定位文件)

根据文件名、文件大小或编辑日期查找文件和目录。

# Find all PNG images under the current directory
find . -name "*.png"

# Locate files modified within the last 24 hours
find . -mtime -1

2. 检查服务器资源和进程

当服务器速度缓慢或遇到内存泄漏时,这些命令有助于诊断问题:

① top/htop(实时过程监控)

列出正在运行的系统进程以及活动 CPU 核心负载和内存指标。

  • htoptop 的流行替代品,具有颜色编码的交互式终端界面。

② df/du(磁盘空间使用情况)

检查磁盘存储限制。

# Check overall disk usage in human-readable (-h) sizes (MB/GB)
df -h

# Check the total size of a specific directory (e.g., node_modules)
du -sh ./node_modules/

③ lsof/netstat(网口监控)

如果启动本地服务器时出现“地址已在使用”错误,请使用此查找占用端口的进程:

# List the Process ID (PID) occupying port 3000
lsof -i :3000

3. 将命令与管道 (|) 和重定向相结合

Linux CLI 的强大之处在于管道 (|),它将一个命令的输出 (stdout) 直接输入到另一个命令的输入 (stdin)。

示例 A:从 access.log 聚合唯一 IP 地址

提取、排序并显示访问您服务器的前 10 个唯一 IP 地址:

# Read the log, extract the IP column, count duplicates, and sort in descending order
cat access.log | awk '{print $1}' | sort | uniq -c | sort -nr | head -n 10
  • awk '{print $1}':仅提取第一个以空格分隔的列(客户端 IP 地址)。
  • sort:对行进行排序(uniq 需要)。
  • uniq -c:对相同的连续行进行重复数据删除,并在每行前面添加其频率计数。
  • sort -nr:以相反(-r - 降序)顺序对输出进行数字排序(-n)。
  • head -n 10:将输出限制为前 10 个结果。

示例 B:强制终止端口阻塞进程

如果本地服务器崩溃而没有释放其端口,请在一行中找到并终止该进程:

# Find the PID for port 3000 and pass it directly to the kill command
kill -9 $(lsof -t -i :3000)

结论

使用 CLI 命令比导航 GUI 菜单或手动打开日志文件更快、更高效。

  1. 使用 grepfind 在几秒钟内找到错误和文件。
  2. 使用 htopdflsof 对系统资源进行故障排除。
  3. 使用管道 (|) 来解析数据的链命令。

在终端中练习将改善您的日常工作流程和基础设施操作。