PullNotifier Logo
Published on

The Ultimate Bash Script Cheat Sheet for Developers

Authors

Welcome to your go-to Bash script cheat sheet, a quick-reference guide packed with the essential commands, syntax, and one-liners every developer needs. Think of this as your toolkit for rapid problem-solving, covering everything from basic file operations and text processing to control structures and even Git automation.

Your Essential Bash Script Quick Reference Guide

A laptop displaying code and a Bash Quick Reference guide on a wooden desk with coffee and plants.

This section is all about speed. It’s designed to give you immediately scannable lists of the most common commands and syntax you'll use day-to-day. No need to dig through dense documentation; the practical, copy-and-paste solutions you need are right here.

The whole point is to help you solve problems directly from your terminal. Whether you're a seasoned dev who just needs a quick reminder or you're just getting started with scripting, this quick reference should be your first stop.

Why This Quick Reference Matters

In software development, automation is everything. It's the key to working smarter, not harder. Bash scripts are the backbone of that automation, handling everything from simple file management to complex CI/CD pipelines. Nailing these fundamentals isn't just about saving time—it's about creating more reliable and consistent development workflows.

This kind of foundational knowledge is especially critical for:

  • Automating development tasks: Scripts can take over repetitive chores like building projects, running tests, and deploying applications.
  • Managing server environments: Any sysadmin or DevOps engineer worth their salt relies on Bash to configure servers, manage users, and keep an eye on system health.
  • Enhancing Git workflows: You can write simple scripts to automate branch cleanup, run pre-commit checks, or handle other version control tasks that keep your repository clean.

Bash in Modern Development Workflows

In today's development world, Bash scripts are a crucial tool for automating GitHub workflows, especially when you pair them with tools like PullNotifier that bring pull request notifications right into Slack. Looking at historical data, it's projected that by 2026, over 400 million repositories on GitHub will contain Bash scripts. GitHub Actions is already executing a mind-boggling 5 million workflows daily, and a huge number of those are powered by Bash.

Bash scripting is also a workhorse for all sorts of system tasks. For a great real-world example, look at something like automating uninstall processes. It’s a perfect illustration of how a simple script can handle software removal cleanly and efficiently—a common and necessary task for maintaining any dev environment.

Mastering Bash Variables and Parameter Expansion

Variables are the bread and butter of any script, acting as named containers for storing data. A common stumbling block for newcomers to Bash is variable assignment—you have to do it without any spaces around the equals sign.

One space is all it takes to break things.

# Correct assignment - no spaces!
WEBSITE="example.com"

# Incorrect assignment (this will cause an error)
# WEBSITE = "example.com"

To get the value back out, you just prefix the variable name with a dollar sign ($). For example, echo $WEBSITE will print "example.com" right to your terminal.

Understanding Scope and Quoting

The scope of a variable determines where it can be accessed. By default, variables are global and available throughout the entire script. But if you need to limit a variable's visibility to just one function, you can declare it as a local variable using the local keyword.

Quoting is another critical concept that dictates how Bash interprets your variables. It’s something you have to get right.

  • Double quotes ("): These are your go-to for most situations. They allow for variable and command substitution, so echo "My site is $WEBSITE" will correctly display the variable's value.
  • Single quotes ('): These treat every single character literally. echo 'My site is $WEBSITE' will print the literal string $WEBSITE, which is rarely what you want.

When in doubt, use double quotes. It's the safest bet for avoiding unexpected behavior, especially when your variables contain special characters.

Power Up with Parameter Expansion

This is where Bash really starts to show its power. Parameter expansion gives you a whole suite of built-in tools for string manipulation right in the shell. You can modify variable content on the fly without needing external commands like sed or awk for simple tasks.

Mastering parameter expansion is the key to writing clean, efficient, and robust scripts that can gracefully handle missing input or format data correctly. For example, you can provide a fallback value if a variable isn't set. The syntax ${VAR:-default} returns "default" if VAR is unset or empty—perfect for setting default configurations.

This quick-reference table breaks down some of the most useful parameter expansion techniques you'll use day-to-day.

Common Bash Parameter Expansion Techniques

OperatorSyntax ExampleDescription
Default Value${VAR:-"default"}Use "default" if VAR is unset or null.
Assign Default${VAR:="default"}Assigns "default" to VAR if it is unset or null.
Substring${VAR:7:4}Extracts 4 characters starting from index 7.
Replace First${VAR/pattern/string}Replaces the first match of pattern with string.
Replace All${VAR//pattern/string}Replaces all matches of pattern with string.
Remove Prefix${VAR#prefix}Removes shortest matching prefix from the start.
Remove Suffix${VAR%suffix}Removes shortest matching suffix from the end.

Getting comfortable with these operators will make your scripts shorter, more readable, and much more resilient. It's a small set of tools with a huge impact on your effectiveness as a scripter.

Controlling Script Flow with Conditionals and Loops

A laptop screen displays 'Control Flow' text, with blurred books on a wooden desk.

To write scripts that are actually useful, you need to tell them how to make decisions and handle repetitive work. That’s where control structures like conditionals and loops come in. They’re the logical backbone of any decent Bash script.

Without them, a script just runs the same set of commands top-to-bottom, every single time. With control flow, you can build in some intelligence: check if a file exists before you try to use it, process a whole list of items one by one, or even retry a command that failed until it works.

Making Decisions with Conditional Statements

Conditional logic is what allows your script to react to different situations. Bash gives you a few ways to run code only if a certain condition is true or false. The classic structure here is the if, elif, else block, which lets you check a series of conditions in order.

A huge part of any if statement is the test condition itself, which you'll almost always see inside double square brackets: [[ ... ]]. This is the modern, Bash-specific syntax, and it's a big improvement over the old single-bracket [ ... ]. It’s just safer and more powerful, especially when you're dealing with strings.

  • File Tests: Check things about files. [[ -f "filename" ]] checks if a regular file exists, while [[ -d "directory" ]] checks for a directory.
  • String Comparisons: Compare text using operators like == for equality and != for inequality. A common one is checking the current user: [[ "$USER" == "root" ]].
  • Numeric Comparisons: Use operators like -eq (equal), -ne (not equal), -gt (greater than), and -lt (less than). For example, [[ $count -gt 10 ]].

Best Practice Tip: Always, always quote your variables inside test conditions, like [[ "$var" == "value" ]]. This is a classic rookie mistake. Without quotes, your script will crash and burn if the variable is empty or contains spaces.

Automating Repetitive Tasks with Loops

Loops are your best friend for any repetitive task. This concept is a core part of our Bash script cheat sheet because it's what lets you, say, process every single file in a folder or run a command on a list of servers without copy-pasting code.

Bash has a few different kinds of loops, each designed for a specific job.

  • For Loops: These are perfect when you're iterating over a known set of items. Think things like files in a directory (for file in *.txt), a sequence of numbers (for i in {1..5}), or even the output from another command.
  • While Loops: A while loop will keep running a block of code as long as its condition stays true. This is the go-to for tasks like reading a file line-by-line or trying a command over and over until it finally succeeds.
  • Until Loops: This one is just the opposite of a while loop. It runs as long as its condition is false. It's really handy when you need to wait for something to happen, like a service to start up or a file to appear.

Writing Reusable Code with Bash Functions and Arrays

If you find yourself writing the same lines of code over and over, it’s time to start using functions. A Bash function is just a block of code you can name and reuse anywhere in your script. This is a game-changer for making your scripts cleaner, easier to read, and a whole lot simpler to debug.

Defining a function is easy: just give it a name and wrap the commands in curly braces. To run the code, you call the function by its name, just like any other command. This simple trick is a cornerstone of any good bash script cheat sheet.

# Define a simple function
greet_user() {
  echo "Hello, $1! Welcome to the system."
}

# Call the function and pass an argument
greet_user "Alice"
# Output: Hello, Alice! Welcome to the system.

Functions can also accept arguments, which you access with positional parameters like $1 for the first one, $2 for the second, and so on. They can also return a value—typically an exit code between 0 and 255—to signal success or failure. A return code of 0 is the universal sign for "everything worked."

Organizing Data with Arrays

While functions help organize your code, arrays are perfect for organizing your data. An array is a variable that holds a list of values, which is incredibly useful for managing collections of items like server names, file paths, or usernames without juggling dozens of individual variables.

Bash gives you two main flavors of arrays:

  • Indexed Arrays: Your standard, zero-indexed list. You pull out elements using their numerical position.
  • Associative Arrays: These work more like dictionaries or hash maps, letting you use custom string keys instead of numbers to access values.

Here’s a quick look at an indexed array in action. Note how we declare it, access an element, and even add a new one.

# Declare an indexed array of servers
servers=("server-db-01" "server-web-01" "server-api-01")

# Access the second element (index 1)
echo "Pinging ${servers[1]}..."
# Output: Pinging server-web-01...

# Add a new server to the array
servers+=("server-worker-01")

# Print all elements
echo "All servers: ${servers[@]}"

When you start combining functions and arrays, you can write some seriously powerful and maintainable scripts. Imagine a function that takes an array of servers and runs a health check on each one. This kind of modular design is the same core principle you’d use to create reusable GitHub Actions, letting you build out some pretty sophisticated automation pipelines.

Handling Input Output And Redirection

A computer monitor displays 'i/O Redirection' on a wooden desk with a plant, notebook, and glasses.

Every Bash script depends on directing data in and out smoothly. At its core, Bash defines three standard streams, each tied to a numeric file descriptor. Grasping these channels is your first step toward writing adaptable, robust scripts.

These streams form the backbone of all command interactions:

  • Standard Input (stdin, fd 0): Accepts data—often from your keyboard or piped commands.
  • Standard Output (stdout, fd 1): Emits regular, successful results to your terminal (or wherever you choose).
  • Standard Error (stderr, fd 2): Conveys error messages so you can separate failures from normal output.

Common Redirection Operators

Redirecting these streams turns one-off commands into powerful workflows. Use the operators below to save outputs, feed files into scripts, or channel errors into logs. This is the heart of our bash script cheat sheet.

OperatorExampleDescription
>ls -l > file.txtRedirects stdout, overwriting file.txt.
>>echo "New line" >> file.txtAppends to file.txt, preserving existing lines.
<sort < unsorted.txtFeeds unsorted.txt into a command as stdin.
2>rm nonexistent 2> error.logSends stderr (errors only) to error.log.
&>command &> all_output.logCaptures both stdout and stderr in one file.

Chaining Commands With Pipes And Here Documents

Often, you’ll string commands together rather than writing intermediate files. The pipe (|) operator takes the stdout of one command and hands it off as stdin to the next. It’s perfect for on-the-fly filtering:

  • Example: cat /var/log/syslog | grep "error" quickly zeroes in on error messages.

When you need to embed a block of text directly into a script—without touching an external file—a here document (<<) is the ticket. It lets you define multi-line input inline:

# Example of a Here Document
wc -l <<EOF
This is line one.
This is line two.
EOF
# The output will be: 2

With these tools in your arsenal, redirecting data and building complex one-liners becomes second nature. Cross-reference this section when you need to:

  • Send outputs and errors to separate files
  • Chain multiple utilities without temp files
  • Embed configurations or message blocks directly in scripts

Automating Git Workflows with Bash Scripts

A laptop displaying code with 'GIT Automation' text, a notebook with drawings, and a pencil on a wooden desk.

Bash scripts are perfect for turning tedious, daily Git tasks into simple, reusable commands. Think of them as your personal toolkit for enforcing team standards and cutting down on manual work, all in a format that's easy to reference for a bash script cheat sheet.

A classic example is a bulk repository clone script that can pull down dozens of projects in one go. Another is a script that automatically cleans up stale branches, keeping your repository tidy. These aren't just for convenience; they genuinely speed up review cycles.

Pull request bottlenecks are a huge time sink. In repos with heavy traffic, automation can slash review time by as much as 55%.

Real-world data shows that across 54 PRs per developer, automation scripts cut lead time from 7 hours 21 minutes down to 4 hours 43 minutes—a 35% improvement. At the same time, the total number of changes requested dropped to just 4 per 78 PRs. You can dig into these findings for more details.

Bulk Cloning and Branch Cleanup

A simple for loop is all you need to iterate through a list of repository URLs and clone each one into a specific folder. It’s a massive time-saver.

  • First, define an array with your repo URLs and set a target directory.
  • Loop through the array, running a git clone command for each one.
  • It's smart to add conditional checks to handle any errors if a clone fails.
repos=("repo1.git" "repo2.git" "repo3.git")
target_dir="projects"
mkdir -p "$target_dir"
for repo in "${repos[@]}"; do
  git clone "git@github.com:$repo" "$target_dir/$(basename "$repo" .git)"
done

This little script completely removes the need for manual cloning and makes sure every project lands in a consistent folder structure. Next up, let's look at how to enforce some quality gates on your pull requests.

Automating PR Validation

With Bash, it’s incredibly easy to wire up linters or tests into your pre-commit hooks or CI/CD jobs. Before any changes get merged, you can automatically run tools like eslint or pytest. By automating these checks, you guarantee that only high-quality code makes it to your main branch.

Ensuring code quality at every step reduces review iterations and speeds delivery.

You can attach this kind of script to a GitHub Actions workflow to run checks automatically on every pull request. This approach works great alongside a tool like PullNotifier, which can then send notifications to Slack only for PRs that have already passed your automated checks. We've got a whole guide on using GitHub Actions to send Slack notifications if you're interested.

Finally, you can schedule routine maintenance tasks using cron. If you need to automate scripts for things like nightly cleanups, an online Crontab Generator can help you create the right entries without the guesswork.

# Run cleanup branch script at midnight daily
0 0 * * * /usr/local/bin/cleanup-branches.sh

These examples are perfect, direct entries for your bash script cheat sheet on Git automation. Having copy-pasteable commands ready to go helps teams adopt standards quickly and consistently.

  • Always run git diff previews before you let a script automatically delete branches.
  • Keep your local workspace clean by regularly running git fetch --prune.
  • Schedule your maintenance scripts with cron for fire-and-forget consistency.

One last tip: always test your scripts thoroughly. Use the -n option for a dry run where possible, log your script's output, and always validate on a test repository first.

Advanced Text Processing with Grep, Sed, and Awk

Sure, basic text processing gets the job done, but mastering the command-line trio of grep, sed, and awk is what really separates a scripting novice from an expert. This part of our Bash script cheat sheet dives into some powerful snippets for the heavy lifting: complex data extraction, log analysis, and configuration management. These tools are your best friends for automating text manipulation that would otherwise be painfully tedious.

grep is your go-to for finding lines that match a pattern, but its real power is unlocked with regular expressions. Forget searching for simple strings; with regex, you can define complex patterns to pinpoint specific data formats, like error codes or usernames buried in massive log files.

Then there's sed, the stream editor, which is a beast at search-and-replace operations. You can modify files directly in place, making it perfect for tasks like updating a database hostname across multiple config files or refactoring variable names throughout a project.

Powerful One-Liner Snippets

To get you started, here are a few practical one-liners that show just what these utilities can do.

  • Grep for Advanced Pattern Matching

    • grep -E 'error|warning' log.txt: Finds all lines containing either "error" or "warning" by using extended regular expressions.
    • grep -oP '(?<=user=)\w+' auth.log: Extracts only the usernames that come right after "user=" using a Perl-compatible regex with a lookbehind. Super useful for parsing specific values.
  • Sed for In-place Editing

    • sed -i 's/old_db_host/new_db_host/g' config.yaml: Replaces every instance of an old database hostname with a new one, saving the change directly back into the config file.
    • sed -i '/^#/d' settings.conf: Instantly deletes all commented-out lines (any line starting with #) from a settings file. A quick way to clean things up.

awk is especially powerful for structured data. It processes text column by column, making it ideal for parsing CSV files or formatted log outputs without writing a complex script.

Finally, we have awk, which is basically a full-blown scripting language designed for slicing and dicing column-based data.

  • Awk for Column-Based Processing
    • awk '{print $1, $4}' access.log: Prints just the first and fourth columns from an access log—a perfect way to isolate IP addresses and response codes.

Common Questions and Quick Answers

Every developer hits a few common bumps in the road when they're deep in a Bash script. Let's clear up some of the usual suspects so you can get back to building.

What's the Real Difference Between #!/bin/sh and #!/bin/bash?

This is a classic "gotcha." You'll see both shebangs out in the wild, but they do very different things. #!/bin/sh points to the system's default shell, which is designed to be POSIX-compliant. On some systems that might be Bash, but on others (like Debian or Ubuntu), it's often a much simpler shell called dash.

The key takeaway? If your script uses any Bash-specific features—think associative arrays (declare -A), certain parameter expansions, or the [[ ... ]] conditional expression—you must use #!/bin/bash. Sticking with the Bash-specific shebang ensures your script behaves predictably everywhere and won't crash with weird syntax errors on a system where /bin/sh isn't Bash.

When Should I Use Bash Instead of Python?

Good question. Bash is the king of "glue code." It's brilliant for simple automation tasks that mostly involve stringing together command-line tools, shuffling files around, and kicking off other programs. If you're just automating a few terminal commands, Bash is your best friend.

But when a script starts to get a mind of its own, it's time to switch. Python is a much better choice for anything involving complex data structures, heavy-duty error handling, or talking to APIs. My rule of thumb is this: if a script is pushing past 100-200 lines, it's probably time to think about rewriting it in Python for the sake of your own sanity and long-term maintainability.

A simple but powerful debugging trick is to run your script with the -x flag: bash -x your_script.sh. This tells Bash to print every single command to the terminal right before it's executed, showing you exactly what's happening under the hood.

You can also toggle this mode on and off inside the script itself. Just add set -x to start debugging a specific section and set +x to turn it off. It’s a fantastic way to get a play-by-play of what your code is actually doing.


Stop letting pull request updates get lost in noisy channels. PullNotifier delivers focused, real-time PR notifications directly to Slack, helping your team cut through the clutter and accelerate code reviews. Start streamlining your workflow for free today.