SH

Shell Performance

Performance optimization patterns for Shell/Bash scripts

Details

Language / Topic
shellShell/Bash
Category
Performance

Rules

balanced
- Minimize subshell forks — use `${var//pattern/replacement}` parameter expansion instead of `echo "$var" | sed 's/pattern/replacement/'`.
- Avoid calling external tools (`awk`, `sed`, `cut`) for simple string operations that Bash parameter expansion can handle natively.
- Use `read` with a here-string (`read var <<< "$value"`) to avoid forking a subshell just to split a variable.
- Use `mapfile -t arr < <(command)` instead of `arr=($(command))` — it avoids word splitting on spaces and does not fork an extra subshell.
- Batch multiple `grep` or `sed` operations into a single invocation with multiple patterns rather than piping through separate processes.
- Prefer built-in Bash arithmetic `(( result = a * b ))` over `$(( bc <<< "$a * $b" ))` to avoid forking the `bc` process.
- Use process substitution `<(command)` to avoid writing intermediate results to disk when piping large streams between processes.