Introduction to Bash

Su Suriya Ravichandran Updated 06 Dec 2026
6 min read ·Lesson 1 of 205

Bash is a command interpreter: a program that reads the commands you type (or the commands stored in a file), works out what they mean, and asks the operating system to carry them out. It is the default interactive shell on most Linux distributions, it is available on macOS and on Windows through WSL, and it is the language behind a huge number of automation scripts, deployment tools, and build pipelines. Learning Bash gives you direct control over a computer using text, which is faster, more repeatable, and easier to automate than clicking through a graphical interface.

Understanding the Concept

A computer's operating system is built from two layers that matter here. The kernel is the core of the system. It manages memory, schedules programs, and talks to the hardware. Programs do not usually talk to the kernel directly in a way a human can type. Instead, you need an intermediary that accepts human-readable text and turns it into requests the system understands. That intermediary is a shell, and Bash is one of the most widely used shells.

When you type a command such as ls, Bash does the following:

  1. It reads the line you typed.
  2. It breaks the line into words and applies its own rules (expansions, quoting, redirections).
  3. It decides whether the first word is something Bash handles itself or a program stored on disk.
  4. It starts the work and waits for it to finish, then shows you the result.

Because Bash is also a programming language, the same mechanism works for files. Instead of typing one command at a time, you can save many commands in a file, called a script, and run the whole file. Everything you can type at the prompt can go into a script, and everything in a script can be tried at the prompt.

What Bash Lets You Do

Bash is useful for three broad categories of work:

  • Interactive work. Navigating folders, inspecting files, searching text, and running programs from a terminal.
  • Automation. Combining commands into scripts that rename hundreds of files, back up a database every night, or check whether a website is online.
  • Gluing programs together. Bash can send the output of one program into another program with a pipe, so small tools each doing one job can be combined into larger solutions.

Here is a small example of the third idea. The command below prints a sentence, converts it to upper case, and counts the characters:

echo "hello bash" | tr a-z A-Z | wc -c

Output:

11

The echo command writes hello bash followed by a newline. The pipe symbol | connects that output to the input of tr, which converts lower-case letters to upper case. A second pipe sends the result to wc -c, which counts bytes. The count is 11 because HELLO BASH has ten characters and the newline adds one more.

How a Bash Session Works

When you open a terminal, a Bash process starts and prints a prompt. The prompt is a short piece of text, often ending in $, which tells you that Bash is ready for input. The loop that follows is called a read-evaluate-print loop, and it works like this:

  1. Bash prints the prompt.
  2. You type a line and press Enter.
  3. Bash evaluates the line, which may start programs.
  4. Output appears in the terminal.
  5. Bash prints the prompt again.

You can see which shell you are running by asking for the current process name:

ps -p $$ -o comm=

Output:

bash

The special variable $$ holds the process ID of the current shell. The ps command looks up that process, and -o comm= asks it to print only the command name without a heading. If the answer is bash, you are using Bash.

Your First Look at the Language

Bash scripts are made of a few simple building blocks, which later lessons cover in depth. A short preview shows how they fit together:

greeting="Hello"
name="Asha"
echo "$greeting, $name!"

Output:

Hello, Asha!

Line by line:

  • greeting="Hello" creates a variable. There must be no spaces around the equal sign.
  • name="Asha" creates a second variable.
  • echo "$greeting, $name!" prints text. The dollar sign tells Bash to replace $greeting and $name with the stored values before the command runs.

Bash also supports decisions and repetition. The following example loops over three names:

for city in Chennai Madurai Coimbatore; do
  echo "City: $city"
done

Output:

City: Chennai
City: Madurai
City: Coimbatore

The for loop assigns each word in the list to the variable city, one at a time, and runs the commands between do and done for each value.

Why Bash Is Worth Learning

Bash appears almost everywhere that software is built or operated:

  • Linux servers. Administrators use Bash to manage users, services, logs, and storage.
  • DevOps and CI/CD. Build and deployment pipelines run Bash commands to compile code, run tests, and publish releases.
  • Containers. Many container images include Bash, and container start-up scripts are frequently Bash scripts.
  • Developer machines. Developers use Bash to run version control, start local servers, and set up projects.

The shell is also stable. Scripts written many years ago still run today, because the core language changes slowly. That makes the skills in this tutorial long-lasting.

Interactive Use and Scripts Compared

The same commands work in both modes, but the two modes serve different purposes.

AspectInteractive useScript
Where commands come fromYour keyboardA file
RepeatabilityYou retype or recall from historyRun the file again at any time
FeedbackImmediate, one command at a timeOutput for the whole run
Typical useExploring and one-off tasksAutomation and shared tools

A script is simply the commands you would have typed, saved in a file. For example, this script prints the current date and the current folder:

#!/usr/bin/env bash
date
pwd

If you save it as info.sh and run it with bash info.sh, Bash executes the two commands in order. The first line, beginning with #!, is called a shebang. It tells the system which interpreter should run the file, and a later lesson explains it in detail.

What This Tutorial Covers

The lessons in this series move from the basics toward real automation work:

  • Fundamentals: shells, terminals, installing Bash, and running commands.
  • Everyday commands for files, directories, and text.
  • Scripting: variables, quoting, input and output, conditions, loops, functions, and arrays.
  • Reliable scripts: exit codes, error handling, and debugging.
  • Advanced topics: security, testing, portability, and automation.
  • Hands-on projects that combine these skills.

Each lesson builds on the earlier ones, so working through them in order gives the smoothest path from first command to working automation.

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 Introduction to Bash and get answers drawn from it.

Signed-in readers only.