Performance Tips for Bash Scripts
Bash is not a fast language. It interprets each line as it runs, stores everything as strings and has no compiler to optimize anything. Yet most slow shell scripts are not slow because of Bash itself. They are slow because of how many programs they start. Every $(...), every pipe and every external command such as cut, grep or date creates a new process, and creating processes is thousands of times more expensive than evaluating a built-in expression. A script that starts a few processes per line of input becomes unusable on a large file, while a script that hands the bulk work to a single awk or sort process stays fast.
This lesson shows how to measure where a script spends its time and then goes through the techniques that matter most, each with measurements. All timings were taken on the same machine (Ubuntu 24.04, Bash 5.2, 2 CPU cores). Absolute numbers will differ on other hardware, but the ratios between approaches are what matter, and they are similar everywhere.
Measure Before Optimizing
Guessing where time goes is unreliable. Measuring is easy, and it should always come first.
time and TIMEFORMAT
The time keyword measures a command, a pipeline or a whole block:
time ./hourly-report.sh access.log > report.txt
real 0m1.087s
user 0m1.025s
sys 0m0.062s
- real is the wall-clock time, what a person waiting actually experiences.
- user is CPU time spent running the programs' own code.
- sys is CPU time the kernel spent on their behalf, for example creating processes or reading files.
A high sys share hints at too many processes or tiny reads and writes; real much larger than user + sys means the script is mostly waiting, for the network, the disk or sleep. Because time is a Bash keyword rather than a program, it can time blocks such as time { ...; } and loops. The TIMEFORMAT variable controls its output; TIMEFORMAT='%R s' prints only the real time with three decimals, which is what the measurements in this lesson use.
Timing the Stages of a Script
To find out which part of a longer script is slow, take timestamps between its stages. EPOCHREALTIME (Bash 5.0 and later) holds the current time in seconds with microsecond precision, such as 1796106253.386577. Removing everything except digits turns it into an integer number of microseconds that Bash arithmetic can subtract. Removing all non-digits, rather than just the dot, also works in locales that write a comma as the decimal separator:
#!/usr/bin/env bash
# stages.sh - time the stages of a script with EPOCHREALTIME
set -euo pipefail
stage_start() { stage_name=$1; stage_t0=${EPOCHREALTIME//[!0-9]/}; }
stage_end() {
local t1=${EPOCHREALTIME//[!0-9]/}
printf '%-22s %6d ms\n' "$stage_name" $(( (t1 - stage_t0) / 1000 )) >&2
}
stage_start "copy log"
cp access.log /tmp/stage-copy.log
stage_end
stage_start "count 5xx (awk)"
errors=$(awk '$9 >= 500' /tmp/stage-copy.log | wc -l)
stage_end
stage_start "sort by status"
sort -k9,9 /tmp/stage-copy.log > /tmp/stage-sorted.log
stage_end
echo "server errors: $errors"
copy log 5 ms
count 5xx (awk) 27 ms
sort by status 59 ms
server errors: 14416
The timings go to standard error, so they never mix with the script's real output.
A Line-by-Line Profiler
When a single loop is slow, it helps to know which line costs the time. Bash's trace mode (lesson 184) can do this: if PS4 contains $EPOCHREALTIME and $LINENO, every traced command is logged with a timestamp and its line number, and the time until the next trace line can be charged to that line. The following script automates this:
#!/usr/bin/env bash
#
# profile.sh - show which lines of a Bash script take the most time
#
# Usage: profile.sh SCRIPT [ARGS...]
#
# Runs SCRIPT with tracing enabled. Every traced command is written with a
# timestamp and line number to a trace file; the time until the next trace line
# is charged to that line. Output: the ten most expensive lines.
set -euo pipefail
(( $# >= 1 )) || { echo "Usage: profile.sh SCRIPT [ARGS...]" >&2; exit 2; }
trace=$(mktemp)
trap 'rm -f "$trace"' EXIT
# The traced script's own output goes to /dev/null; the trace goes to fd 3.
bash -c 'PS4="+ \${EPOCHREALTIME} \${LINENO} "; BASH_XTRACEFD=3; set -x; . "$0" "$@"' \
"$@" 3> "$trace" > /dev/null || true
awk -v script="$1" '
$1 ~ /^\+/ && $2 ~ /^[0-9]+[.,][0-9]+$/ {
t = $2; sub(",", ".", t)
if (prev_line != "") { spent[prev_line] += t - prev_t; hits[prev_line]++ }
prev_t = t; prev_line = $3
}
END {
for (l in spent) total += spent[l]
for (l in spent)
printf "%8.3f s %5.1f%% %7d line %s\n", spent[l], 100 * spent[l] / total, hits[l], l
}
' "$trace" | sort -rn | head -n 10 |
{ printf '%10s %6s %7s %s\n' "time" "share" "count" "where (in $1)"; cat; }
How it works:
bash -c '...' "$@"starts a new Bash, setsPS4andBASH_XTRACEFD=3so the trace goes to file descriptor 3 instead of standard error, enablesset -x, and then runs the script with.(source). Insidebash -c,$0is the first argument after the command string (the script) and"$@"are its arguments. ThePS4value is in single quotes inside the outer quotes, with\$so that it is expanded for each traced command, not once at the start.- The
awkprogram reads the trace. For each line it subtracts the previous timestamp and adds the difference to the previous line number, because the time between two trace lines was spent executing the first one.sub(",", ".")handles locales with a decimal comma. - The result is sorted by time and shows each line's share and how many trace lines it produced.
The profile is approximate: commands inside subshells are traced too, and their time is attributed in the order the lines appear. It is still very good at answering the important question of where most of the time goes, as the complete example at the end of this lesson shows.
The Main Cost: Starting Processes
Starting an external program requires the shell to fork (create a copy of itself), and the copy to exec (replace itself with the program, which the system must load and initialize). A command substitution $(...) or a pipeline element costs at least a fork, even when the command inside is a built-in. Built-in commands and expansions run inside the existing shell process and cost almost nothing by comparison.
Each pair below does the same job 1,000 times:
| Task | With a new process | Time | Without | Time |
|---|---|---|---|---|
| File name from a path | n=$(basename "$p") | 1.168 s | n=${p##*/} | 0.002 s |
| Add one | i=$(expr "$i" + 1) | 1.310 s | i=$((i + 1)) | 0.002 s |
| Capture a string | n=$(echo hi) | 0.279 s | printf -v n '%s' hi | 0.002 s |
| Read a small file | x=$(cat allowed.txt) | 1.245 s | x=$(< allowed.txt) | 0.016 s |
| Current time | now=$(date +%s) | 1.236 s | now=$EPOCHSECONDS | 0.003 s |
| Today's date | $(date +%F) | similar | printf -v today '%(%Y-%m-%d)T' -1 | 0.098 s |
Two numbers are worth remembering from this table. An external command in a loop costs about 1.2 milliseconds per iteration here, a command substitution of a built-in about 0.3 milliseconds, while a parameter expansion or arithmetic expansion costs about 2 microseconds: roughly 500 times less. One millisecond sounds harmless, but a loop over 100,000 lines with five external commands per line spends ten minutes just starting programs.
The replacements in the right column are all features covered earlier in this tutorial:
- Parameter expansion (lessons 54 and 152) replaces
basename,dirname,cuton simple strings andsedfor simple substitutions:${p##*/},${p%/*},${line%% *},${s//old/new}. - Arithmetic expansion
$(( ))replacesexprandbcfor integer math. printf -v varstores formatted output directly in a variable, without a subshell. Its%(format)Tconversion formats dates (-1means "now"), replacing most calls ofdateinside loops.EPOCHSECONDSandEPOCHREALTIMEgive the current time as a number.$(< file)reads a file without startingcat. In the measurement above it was much faster than$(cat file).[[ ]]with==patterns or=~regular expressions replacesecho "$x" | grep -q ...for testing a single string.
Counting the Processes
strace -f can count how many programs a script really executes. Three versions of a script that count HTTP status codes in a 1,000-line access log (shown in the next section) were run under strace -f -e trace=execve:
count-cut execve=1002
count-read execve=2
count-awk execve=3
The first version executes 1,002 programs, one cut per line plus bash and sort; the others execute two or three. When a script is slow and you do not know why, counting execve calls is a quick way to confirm that process creation is the cause.
Do Not Process Large Data Line by Line in Bash
The biggest performance mistakes appear in loops over the lines of a file. Here are three ways to count how often each status code (field 9) appears in an access log. Each line of the log looks like this:
10.0.0.8 - - [01/Dec/2026:17:09:16 +0000] "DELETE /api/item/92 HTTP/1.1" 404 3487
Version 1: an external command per line.
#!/usr/bin/env bash
# Version 1: one cut process per line
declare -A count=()
while IFS= read -r line; do
status=$(cut -d' ' -f9 <<< "$line")
count[$status]=$(( ${count[$status]:-0} + 1 ))
done < "$1"
for s in "${!count[@]}"; do printf '%s %d\n' "$s" "${count[$s]}"; done | sort
Version 2: let read split the fields. read with several variable names splits the line on whitespace itself (lesson 31). _ is a conventional name for fields that are not needed; the last variable receives the rest of the line:
#!/usr/bin/env bash
# Version 2: let read split the fields, no external commands in the loop
declare -A count=()
while read -r _ _ _ _ _ _ _ _ status _; do
count[$status]=$(( ${count[$status]:-0} + 1 ))
done < "$1"
for s in "${!count[@]}"; do printf '%s %d\n' "$s" "${count[$s]}"; done | sort
Version 3: one awk process for the whole file.
#!/usr/bin/env bash
# Version 3: one awk process for the whole file
awk '{ count[$9]++ } END { for (s in count) print s, count[s] }' "$1" | sort
All three produce the same result:
200 56847
301 14313
404 14424
500 14416
Their speed is very different:
| Version | Input | Time | Time per line |
|---|---|---|---|
1: cut per line | 10,000 lines | 16.311 s | 1.6 ms |
2: read splits | 100,000 lines | 0.675 s | 6.8 µs |
3: one awk | 100,000 lines | 0.020 s | 0.2 µs |
Version 1 was measured on only a tenth of the file; on all 100,000 lines it would need nearly three minutes. Version 2 is roughly 240 times faster per line, simply because nothing in its loop starts a process. Version 3 is another 30 times faster, because awk is designed for exactly this job: it reads, splits and counts in compiled code instead of interpreting shell commands.
The lesson generalizes: Bash should orchestrate, and tools such as awk, sort, grep and sed should process data. A Bash loop over lines is fine for dozens or hundreds of items such as file names, servers or users, especially when each iteration does real work like copying a file. For thousands of lines of data, move the loop into a single awk program or a pipeline of filters, where every tool runs once over the whole stream.
Other Techniques That Pay Off
Read Data Once
A script that runs grep "$pattern" "$log" once per hour of the day reads the whole log 24 times. Computing all 24 results in one pass, with awk collecting the counts in an array, reads the log once. The more often a script reads the same large input, the more this matters; disk caches soften the cost, but each pass still has to parse every line.
Look Up Values in an Associative Array
Checking every item of one list against another list is a common task: which of 1,000 IP addresses appear in an allow list of 500? Calling grep once per item starts 1,000 processes. Loading the allow list into an associative array (lesson 102) once makes every check a constant-time lookup. A single grep -f over the whole list is the fastest option when only the count or the matching lines are needed:
# 1,000 processes
n=0; while IFS= read -r ip; do grep -qxF "$ip" allowed.txt && n=$((n+1)); done < ips.txt
# one table, no processes
declare -A ok=()
while IFS= read -r ip; do ok[$ip]=1; done < allowed.txt
n=0; while IFS= read -r ip; do [[ -n ${ok[$ip]:-} ]] && n=$((n+1)); done < ips.txt
# one process does everything
grep -cxFf allowed.txt ips.txt
| Approach | Time |
|---|---|
grep per item | 1.159 s |
| associative array | 0.005 s |
one grep -f | 0.001 s |
-F treats each pattern as a fixed string and -x requires the whole line to match, so 10.0.1.2 does not match 10.0.1.20.
Redirect Once, Not in Every Iteration
echo "$x" >> file inside a loop opens and closes the file on every iteration. Redirecting the whole loop opens it once:
for ((i = 0; i < 20000; i++)); do echo "line $i" >> out.txt; done # 0.074 s
for ((i = 0; i < 20000; i++)); do echo "line $i"; done > out.txt # 0.036 s
The difference is a factor of two here, because opening a file is much cheaper than starting a process. It grows with slower file systems such as network shares. The loop-level redirection is also cleaner: the output file is written by exactly one redirection.
Batch Arguments Instead of One Process per File
find -exec cmd {} \; runs the command once per file. find -exec cmd {} + and xargs pass as many file names as fit on one command line, so the command runs a few times instead of thousands of times (lesson 112):
| Command (1,000 files) | Time |
|---|---|
find many -name '*.txt' -exec touch {} \; | 0.951 s |
find many -name '*.txt' -exec touch {} + | 0.004 s |
The same applies to a for loop that calls chmod or rm for each file: chmod 640 -- "${files[@]}" with an array does the work in a single call.
Use Several CPU Cores for Independent Work
When each item requires real computing work, such as compressing files, resizing images or checking many servers, running several items at the same time uses more of the machine. xargs -P N runs up to N commands in parallel:
find par -name '*.log' -print0 | xargs -0 -P 2 -n 1 gzip -k -f
| Compressing eight 39 MB logs | Time |
|---|---|
| one after another | 6.395 s |
xargs -P 2 | 3.218 s |
xargs -P 4 | 3.163 s |
On this 2-core machine, two parallel jobs halve the time; four jobs bring no further gain, because there are no more cores to use. Choose N based on nproc for CPU-bound work. For work that mostly waits, such as network requests, a higher N can help, but be considerate of the servers being contacted. -n 1 passes one file per command; -print0 and -0 keep file names with spaces intact. Lesson 138 shows how to run background jobs with & and wait when the work is not a simple list of files.
Choose the Locale Deliberately
Sorting and case-insensitive matching depend on the locale. In a UTF-8 locale, sort applies language-aware collation rules and grep -i must handle multibyte characters; with LC_ALL=C, both work on plain bytes:
| 500,000 lines | LC_ALL=C.UTF-8 | LC_ALL=C |
|---|---|---|
sort | 0.215 s | 0.163 s |
grep -ci 'delete /api/item/4' | 0.050 s | 0.022 s |
The gain on this machine is moderate; with full language locales such as en_US.UTF-8, whose collation rules are more complex, it is often larger. LC_ALL=C changes results as well as speed: sorting becomes byte order (all uppercase letters before lowercase ones), and non-ASCII letters are not matched case-insensitively. Use it for machine-oriented data such as logs, IDs and hashes, where byte order is exactly what you want, and not for text that people will read in sorted order.
Keep Start-up Cheap for Small Scripts
A script that is called thousands of times, for example by find -exec or a monitoring system, pays its start-up cost every time. Starting bash -c true 200 times took 0.265 s here, Dash 0.185 s. More important than the shell itself is what the script does before its real work: sourcing large libraries, calling several external commands to compute configuration, or loading a full interactive environment. Keep frequently called scripts lean, and never rely on .bashrc in non-interactive scripts (lesson 146).
A Complete Example: Speeding Up an Hourly Report
The following script reads an access log and reports requests, server errors (status 500 and above) and transferred kilobytes per hour. It works, but it was written by someone thinking in terms of "take the line, cut out the part I need":
#!/usr/bin/env bash
# hourly-report.sh - requests, server errors and traffic per hour (first version)
set -euo pipefail
log=$1
declare -A req=() err=() bytes=()
while IFS= read -r line; do
ts=$(echo "$line" | cut -d'[' -f2 | cut -d']' -f1)
hour=$(echo "$ts" | cut -d: -f2)
status=$(echo "$line" | awk '{print $9}')
size=$(echo "$line" | awk '{print $10}')
req[$hour]=$(( ${req[$hour]:-0} + 1 ))
if (( status >= 500 )); then err[$hour]=$(( ${err[$hour]:-0} + 1 )); fi
bytes[$hour]=$(( ${bytes[$hour]:-0} + size ))
done < "$log"
for hour in $(printf '%s\n' "${!req[@]}" | sort); do
printf '%s:00 %6d requests %5d errors %6d KiB\n' \
"$hour" "${req[$hour]}" "${err[$hour]:-0}" "$(( bytes[$hour] / 1024 ))"
done
On 2,000 lines it needs 12.971 seconds, about 6.5 milliseconds per line. A day's log of 100,000 lines would take around eleven minutes.
Step 1: Profile
Running the profiler on a 300-line sample shows where the time goes:
$ ./profile.sh hourly-slow.sh l300.log
time share count where (in hourly-slow.sh)
0.549 s 26.4% 1200 line 8
0.496 s 23.8% 900 line 10
0.483 s 23.2% 900 line 9
0.388 s 18.7% 900 line 11
0.155 s 7.5% 602 line 7
0.002 s 0.1% 343 line 13
0.002 s 0.1% 300 line 14
0.002 s 0.1% 300 line 12
0.002 s 0.1% 26 line 17
0.000 s 0.0% 23 line 18
Lines 8 to 11, the four command substitutions, take 92 percent of the time. Each of them forks a subshell plus one process per pipeline element, so every input line costs more than ten new processes. The counting on lines 12 to 14 is practically free. (Line 7, the while read line, also gets a share, most likely because part of the work of starting the next command substitution happens before its first trace line appears.)
Step 2: Remove the Processes from the Loop
All four values can be taken from the line without any external command. read splits the fields, and a substring expansion extracts the hour from the timestamp field [01/Dec/2026:17:09:16, where the hour starts at offset 13:
#!/usr/bin/env bash
# hourly-report.sh - requests, server errors and traffic per hour (pure Bash loop)
set -euo pipefail
log=$1
declare -A req=() err=() bytes=()
# 10.0.0.8 - - [01/Dec/2026:17:09:16 +0000] "DELETE /api/item/92 HTTP/1.1" 404 3487
while read -r _ _ _ ts _ _ _ _ status size; do
hour=${ts:13:2} # [01/Dec/2026:17:09:16 -> 17
req[$hour]=$(( ${req[$hour]:-0} + 1 ))
if (( status >= 500 )); then err[$hour]=$(( ${err[$hour]:-0} + 1 )); fi
bytes[$hour]=$(( ${bytes[$hour]:-0} + size ))
done < "$log"
for hour in $(printf '%s\n' "${!req[@]}" | sort); do
printf '%s:00 %6d requests %5d errors %6d KiB\n' \
"$hour" "${req[$hour]}" "${err[$hour]:-0}" "$(( bytes[$hour] / 1024 ))"
done
The comment with a sample line documents which field is which, which matters because read assigns fields by position: the fourth field is the timestamp, the ninth the status and the tenth the size. This version is still easy to read for anyone who knows Bash, and it processes the full 100,000-line log in about one second.
Step 3: Let awk Do the Work
For the best performance, the whole computation moves into one awk program. Its substr($4, 14, 2) is the same extraction as ${ts:13:2}, since awk counts from 1:
#!/usr/bin/env bash
# hourly-report.sh - requests, server errors and traffic per hour (one awk pass)
set -euo pipefail
log=$1
awk '
{
hour = substr($4, 14, 2) # [01/Dec/2026:17:09:16 -> 17
req[hour]++
if ($9 >= 500) err[hour]++
bytes[hour] += $10
}
END {
for (h in req)
printf "%s:00 %6d requests %5d errors %6d KiB\n", h, req[h], err[h], int(bytes[h] / 1024)
}
' "$log" | sort
Undefined awk array elements count as 0, so hours without errors need no special treatment, and int() truncates like Bash's integer division. awk returns the hours in no particular order, so sort puts them in order.
Results
All three versions produce byte-for-byte identical reports, verified with cmp:
00:00 4173 requests 610 errors 10108 KiB
01:00 4175 requests 632 errors 10204 KiB
02:00 4257 requests 617 errors 10380 KiB
...
| Version | 2,000 lines | 100,000 lines |
|---|---|---|
| 1: command substitutions per line | 12.971 s | about 11 minutes (estimated) |
2: read and parameter expansion | 0.025 s | 1.055 s |
3: one awk program | 0.004 s | 0.031 s |
The first improvement, removing processes from the loop, gave a factor of about 500 and made the script practical. The second gave another factor of 30. Whether that second step is worth it depends on the situation: for a nightly report, one second is perfectly fine, and the pure Bash version may be easier for a team to maintain; for a script that runs on every request or processes gigabytes, the awk version is the right choice.
Keeping Optimization in Proportion
Performance work has a cost: faster code is sometimes harder to read. A few guidelines keep the balance:
- Optimize what you measured. The profile above pointed at four lines; changing anything else would have been wasted effort.
- Fix the shape before the details. Removing processes from loops and reading data once gives factors of 100 or more. Micro-optimizations such as choosing between two equivalent built-ins rarely matter.
- Keep correctness checks. Each version of the report was compared against the original with
cmp. Tests from lessons 185 to 187 protect a script while its inside is being rewritten. - Know when to leave Bash. If a script spends most of its time on data processing even after these techniques, and
awkbecomes unwieldy, a language such as Python may be the better tool for that part, with Bash still orchestrating the surrounding steps.