Stop piping grep to head and just use -m
Shell Scripting / Bash Tricks
Stop piping grep to head and just use -m
🧩 The Challenge
You are digging through a massive log file looking for the first few errors and end up using a pipe to head, which forces the system to scan way more data than it actually needs to. It drives me crazy when I see people waste I/O like that on a production box.
💡 The Fix
Most people don’t realize that grep has a built-in flag to stop processing once it finds a specific number of matches. It’s cleaner and way faster since it drops the connection to the file immediately.
grep -m 5 "ERROR" /var/log/syslog
⚙️ Why It Works
Setting the max-count flag tells the grep binary to exit silently after it hits the target number of matches, preventing it from reading the rest of your gargantuan log file.
🚀 Pro-Tip: Use -m 1 if you just need to confirm a specific service finished its startup routine.
Linux Tips & Tricks | © ngelinux.com | 9/27/2026
