Performance Tips for Bash Scripts

Su Suriya Ravichandran Updated 06 Dec 2026
19 min read ·Lesson 191 of 205

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, sets PS4 and BASH_XTRACEFD=3 so the trace goes to file descriptor 3 instead of standard error, enables set -x, and then runs the script with . (source). Inside bash -c, $0 is the first argument after the command string (the script) and "$@" are its arguments. The PS4 value is in single quotes inside the outer quotes, with \$ so that it is expanded for each traced command, not once at the start.
  • The awk program 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:

TaskWith a new processTimeWithoutTime
File name from a pathn=$(basename "$p")1.168 sn=${p##*/}0.002 s
Add onei=$(expr "$i" + 1)1.310 si=$((i + 1))0.002 s
Capture a stringn=$(echo hi)0.279 sprintf -v n '%s' hi0.002 s
Read a small filex=$(cat allowed.txt)1.245 sx=$(< allowed.txt)0.016 s
Current timenow=$(date +%s)1.236 snow=$EPOCHSECONDS0.003 s
Today's date$(date +%F)similarprintf -v today '%(%Y-%m-%d)T' -10.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, cut on simple strings and sed for simple substitutions: ${p##*/}, ${p%/*}, ${line%% *}, ${s//old/new}.
  • Arithmetic expansion $(( )) replaces expr and bc for integer math.
  • printf -v var stores formatted output directly in a variable, without a subshell. Its %(format)T conversion formats dates (-1 means "now"), replacing most calls of date inside loops. EPOCHSECONDS and EPOCHREALTIME give the current time as a number.
  • $(< file) reads a file without starting cat. In the measurement above it was much faster than $(cat file).
  • [[ ]] with == patterns or =~ regular expressions replaces echo "$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:

VersionInputTimeTime per line
1: cut per line10,000 lines16.311 s1.6 ms
2: read splits100,000 lines0.675 s6.8 µs
3: one awk100,000 lines0.020 s0.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
ApproachTime
grep per item1.159 s
associative array0.005 s
one grep -f0.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 logsTime
one after another6.395 s
xargs -P 23.218 s
xargs -P 43.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 linesLC_ALL=C.UTF-8LC_ALL=C
sort0.215 s0.163 s
grep -ci 'delete /api/item/4'0.050 s0.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
...
Version2,000 lines100,000 lines
1: command substitutions per line12.971 sabout 11 minutes (estimated)
2: read and parameter expansion0.025 s1.055 s
3: one awk program0.004 s0.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 awk becomes unwieldy, a language such as Python may be the better tool for that part, with Bash still orchestrating the surrounding steps.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Performance Tips for Bash Scripts and get answers drawn from it.

Signed-in readers only.