Interview Prep/Shell Scripting/Troubleshooting: tools, portability, permissions and environment

A log-summary script that took 2 minutes now takes 3 hours since traffic grew. `strace -c -f` shows millions of `clone` and `execve` calls.

AdvancedTroubleshootingTroubleshooting: tools, portability, permissions and environment
Answer

Likely causes → The script runs external commands per line: while read line; do ip=$(echo "$line" | cut -d' ' -f1); ts=$(date -d ...); ... done. Each $(...) with a pipe forks one or more processes, so 4 million lines means tens of millions of forks. Runtime scales with the number of lines times the cost of a fork.

Diagnose →

strace -c -f -o /tmp/st.txt ./summary.sh access.log.sample; sort -k4 -rn /tmp/st.txt | head
bash -x ./summary.sh sample.log 2>&1 | grep -c '^+.*cut'      # forks per line

Fix → Move the per-line work into a single process. One awk pass replaces the whole loop:

awk '$9 ~ /^5/ { errors[$1]++; total++ }
     END { for (ip in errors) printf "%d %s\n", errors[ip], ip; print total > "/dev/stderr" }' \
  access.log | sort -rn | head -n 20

Inside Bash loops that must stay, use builtins: ${line%% *} instead of cut, printf '%(%F)T' instead of date, [[ =~ ]] instead of grep.

Prevent → Rule of thumb: no external command inside a loop over data lines. If the logic outgrows one awk program, it is time for Python or Go.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: tools, portability, permissions and environment