Beginners Guide: Overview, Features, and Learning Path
This page gives you a complete overview of Bash, explains what each feature does, and guides you through a recommended learning order. It covers what Bash is, its characteristics and trade-offs, how execution works, and a summary of the major features.
What Is Bash?
Bash (pronounced "bash") is a shell for Unix-based operating systems. A shell is a program that acts as a bridge between the user and the kernel (the core of the OS), letting you send commands to the computer.
Bash stands for "Bourne Again SHell." It was created in 1989 by Brian Fox as an improved and extended version of the original Unix shell, the Bourne Shell (sh). It ships as the default shell on most macOS and Linux systems.
The full history of Bash (the 1977 Bourne shell, Brian Fox's 1989 development under the GNU project, the spread alongside Linux, and where shells stand today) is covered in the IT Terms & History Dictionary entry on Bash.
Terminal vs. Shell
These two terms are often confused, but they serve different roles.
| Terminal (Emulator) | Shell | |
|---|---|---|
| Role | The "screen" that displays text and accepts input | The "processing engine" that interprets and runs commands |
| Examples | macOS Terminal.app, iTerm2 | bash, zsh, sh |
The terminal is the window used to run a shell. When you open a terminal, a shell (such as Bash) starts inside it and waits for your input.
Command Line Interface (CLI)
Bash is a typical implementation of the CLI (Command Line Interface). A CLI is an interface where you operate the computer by typing text commands. It contrasts with a GUI (Graphical User Interface), where you click icons with a mouse.
Bash's Characteristics and Trade-offs
What Bash Does Well
| Feature | Details |
|---|---|
| Comes preinstalled | Available on macOS and Linux with no installation needed; practically guaranteed on server environments |
| Pipes and redirection | Combine commands to express complex operations in a single line |
| Scripting | Automate repetitive tasks; combine with cron for scheduled execution |
| Text processing | Powerful integration with tools like grep, sed, and awk |
| Long history | In use since 1989; rich documentation and community resources |
Where Bash Can Be Awkward
| Aspect | Details |
|---|---|
| Unique syntax | Rules differ from languages like Python or PHP — for example, spaces around = change the meaning |
| Error handling | Scripts continue running even when a command fails by default; set -e changes this behavior |
| No types | All values are essentially strings; arithmetic requires special notation |
| Complex logic | For large-scale logic, alternatives such as Python or Ruby are an option |
| Portability | Bash-specific features (bashisms) may not work under sh |
Bash is well-suited for server administration, file operations, and automating routine tasks. For implementing large-scale business logic, other languages are often more appropriate. This is not a matter of which is better — different tasks call for different tools.
How Execution Works
Understanding what happens between entering a command and seeing the result makes it easier to diagnose errors.
When you type a command, Bash first interprets it. It expands variables, processes pipes and redirections, searches for the command (using $PATH), and finally asks the kernel to run it.
Script Execution Flow
Instead of entering commands one at a time, you can save multiple commands in a script file (.sh file) and run them all together.
#!/bin/bash # Shebang line: declares this file is run with bash name="Kiryu" echo "Hello, $name"
Run the following command:
chmod +x greet.sh ./greet.sh Hello, Kiryu
The first line #!/bin/bash is called a shebang. It tells the system "please run this file with /bin/bash." See Shebang / chmod +x for details.
Basic Commands — Files and Directories
These are the commands you need first when working with Bash.
| Command | Description | Common Example |
|---|---|---|
ls | List files in a directory | ls -la (detailed list including hidden files) |
cd | Change directory | cd /var/log |
pwd | Print working directory | pwd |
cp | Copy files or directories | cp file.txt backup.txt |
mv | Move or rename | mv old.txt new.txt |
rm | Delete files or directories | rm -rf dir/ (recursive; use with caution) |
mkdir | Create a directory | mkdir -p a/b/c (create intermediate directories too) |
touch | Create an empty file or update timestamp | touch file.txt |
mkdir project cd project touch readme.txt ls -la cp readme.txt readme_backup.txt pwd /home/kazuma/project
See ls, cd / pwd, cp / mv / rm, and mkdir / rmdir / touch for details.
Variables
Bash lets you store values in variables and reuse them. One key difference from most programming languages: no spaces are allowed around = when assigning a value.
# Assign a value (no spaces around =) name="Kiryu Kazuma" age=47 # Reference a variable (prefix with $) echo "Name: $name" echo "Age: $age" Name: Kiryu Kazuma Age: 47
Quote Types
name="Majima" # Double quotes: variables are expanded echo "Hello, $name" # Hello, Majima # Single quotes: no expansion (everything is treated literally) echo 'Hello, $name' # Hello, $name Hello, Majima Hello, $name
See Variable Definition and Reference for details, and Special Variables for $?, $0, $$, and others.
Conditionals — if
The if statement lets Bash take different actions depending on a condition. Note that spaces inside [ ] or [[ ]] are required — this is a common source of confusion for newcomers.
score=85
if [ $score -ge 80 ]; then
echo "Pass: $score points"
elif [ $score -ge 60 ]; then
echo "Retake: $score points"
else
echo "Fail: $score points"
fi
Pass: 85 points
Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
-eq | Equal to | [ $a -eq $b ] |
-ne | Not equal to | [ $a -ne $b ] |
-gt | Greater than | [ $a -gt 10 ] |
-lt | Less than | [ $a -lt 10 ] |
-ge | Greater than or equal to | [ $a -ge 10 ] |
-le | Less than or equal to | [ $a -le 10 ] |
= | Strings are equal | [ "$str" = "hello" ] |
!= | Strings are not equal | [ "$str" != "hello" ] |
-z | String is empty | [ -z "$str" ] |
-f | File exists | [ -f "/etc/hosts" ] |
-d | Directory exists | [ -d "/tmp" ] |
See if / elif / else for the full syntax, and test / Conditionals for all conditional expression forms.
Loops — for / while
for Loop
Repeats a block of commands for each item in a list.
# Iterate over a list of values
for member in Kiryu Majima Nishikiyama; do
echo "Member: $member"
done
Member: Kiryu Member: Majima Member: Nishikiyama
The following example demonstrates this:
# Numeric range (1 to 5)
for i in {1..5}; do
echo "No. $i"
done
No. 1 No. 2 No. 3 No. 4 No. 5
while Loop
Repeats as long as a condition is true.
count=1
while [ $count -le 3 ]; do
echo "Count: $count"
count=$((count + 1))
done
Count: 1 Count: 2 Count: 3
See for and while / until for details.
Functions
Functions let you group commands under a name and call them repeatedly. Arguments are accessed with $1, $2, ... — unlike most languages, there is no argument list in the function signature.
# Define a function
greet() {
local name=$1 # $1 is the first argument
echo "Hello, $name!"
}
# Call the function
greet "Kiryu"
greet "Majima"
Hello, Kiryu! Hello, Majima!
Return Values
Bash functions can only return a number (exit code) directly. To "return" a string, use command substitution: print the value with echo and capture it with $().
# Return a string via echo and command substitution
get_name() {
echo "Kiryu Kazuma"
}
result=$(get_name)
echo "$result"
Kiryu Kazuma
See Function Definition and Function Arguments and Return Values for details.
Pipes and Redirection
Pipes and redirection are one of Bash's greatest strengths. They let you combine multiple commands to express complex processing in short, readable code.
Pipe (|)
The pipe | passes the output of the command on the left to the input of the command on the right.
# Pass ls output to grep to filter .txt files only ls -la | grep ".txt"
The same logic can also be written as:
# Read a file, sort lines, remove duplicates, count remaining lines cat names.txt | sort | uniq | wc -l
Redirection
| Symbol | Meaning | Example |
|---|---|---|
> | Write stdout to a file (overwrite) | echo "hello" > out.txt |
>> | Append stdout to a file | echo "world" >> out.txt |
< | Read a file as stdin | sort < list.txt |
2> | Write stderr to a file | cmd 2> err.log |
&> | Write both stdout and stderr to a file | cmd &> all.log |
See Pipe, Redirection (Output), and Redirection (Input) / Here Document for details.
Text Processing — grep / sed / awk
One reason Bash is so powerful for server administration and automation is its integration with text-processing tools.
grep — Search and Filter Lines
Extracts lines from a file or stdin that match a pattern.
# Extract lines containing "error"
grep "error" app.log
# -i: case-insensitive search
grep -i "Error" app.log
# -n: show line numbers
grep -n "error" app.log
# Extended regex: lines with 3 or more consecutive digits
grep -E "[0-9]{3,}" data.txt
sed — Stream Editor for Substitution and Transformation
Transforms file content. The most common use is string substitution.
# Replace "Kiryu" with "Akiyama" and print the result sed 's/Kiryu/Akiyama/' names.txt # -i: edit the file in place (macOS requires -i '') sed -i 's/old/new/g' file.txt
awk — Extract Columns and Aggregate Data
Extracts specific columns from space- or tab-delimited text, or performs aggregations.
# Print the second column (space-delimited)
awk '{print $2}' data.txt
# Print rows where the third column is 100 or more
awk '$3 >= 100' scores.txt
See grep, sed, awk, and wc / sort / uniq for details.
File Operations
These commands let you inspect and process file contents.
| Command | Description |
|---|---|
cat | Display the full contents of a file |
head | Display the first N lines of a file (default: 10) |
tail | Display the last N lines; -f follows new output in real time |
less | Browse a file page by page (good for large files) |
wc | Count lines, words, and bytes |
sort | Sort lines |
uniq | Remove consecutive duplicate lines (pairs well with sort) |
find | Search for files matching given criteria |
tar | Archive, compress, or extract files |
# Display the last 100 lines in real time tail -f /var/log/app.log # Search for files with a specific extension find /home/date -name "*.log" -type f # Archive a directory and compress with gzip tar czf backup.tar.gz project/
See head / tail, wc / sort / uniq, find, and tar for details.
Process Management
Monitoring and controlling running processes is another important use of the shell.
| Command | Description |
|---|---|
ps | List running processes |
top | Show CPU (Central Processing Unit — the processor that executes computations) and memory usage in real time |
kill | Terminate a process by its PID (process ID) |
pkill | Terminate processes by name |
& | Run a command in the background |
# List all running processes ps aux # Search for a process named "nginx" ps aux | grep nginx # Terminate process with PID 1234 kill 1234 # Run a script in the background ./long_process.sh &
See ps / top / htop, kill / pkill / killall, and Background Jobs for details.
Common Errors and How to Fix Them
command not found
command not found appears when the command you typed cannot be located. Possible causes: the command is not installed, the name is misspelled, or the command's directory is not in $PATH.
greet -bash: greet: command not found
Use which to find where a command lives.
which bash /bin/bash
Spaces Around = in Variable Assignment
No spaces are allowed around = when assigning a variable. With spaces, Bash tries to run name as a command.
name = "Kiryu" # Error: Bash tries to run "name" as a command name="Kiryu" # Correct
Missing Spaces Inside [ ]
There must be spaces immediately inside [ and before ] in a conditional expression.
if [$count -eq 1]; then # Error: Bash looks for a command named "[1" if [ $count -eq 1 ]; then # Correct
Script Has No Execute Permission
If running ./script.sh shows "Permission denied", the file is not marked as executable. Add the permission with chmod +x.
chmod +x script.sh ./script.sh
Windows Line Endings (CRLF) in the Script
Scripts created on Windows may have CRLF line endings that cause errors on Linux or macOS. Convert them with dos2unix.
dos2unix script.sh
Writing Comments
In a Bash script, comments are written with #. Everything from # to the end of the line is ignored when the shell runs the script. Bash has no dedicated block comment syntax; multi-line comments are written by placing # at the start of each line.
Types of Comments
| Type | Syntax | Description |
|---|---|---|
| Single-line comment | # text | Everything from # to the end of the line becomes a comment. Also used as an inline note after code. |
| Shebang | #!/usr/bin/env bash | A special #! line written on the very first line of a script. It tells the OS which shell to use for execution. Not a comment, but starts with the same # character. |
Example
#!/usr/bin/env bash
# backup.sh — compress a target directory into a tar.gz archive
# Argument check: show usage and exit if exactly one argument is not given
if [ "$#" -ne 1 ]; then
echo "Usage: $0 " >&2
exit 1
fi
TARGET="$1"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
OUTPUT="${TARGET%/}_${TIMESTAMP}.tar.gz"
# Use -- to safely handle directory names that start with a hyphen
tar czf "$OUTPUT" -- "$TARGET"
echo "Saved: $OUTPUT"
Comments can hold whatever you find useful. Common uses include why the code is written a certain way, what the code does, TODOs, and notes — but you are free to write whatever fits the situation. For conventions around commenting out code temporarily and further details, see the comment reference page.
Recommended Learning Order
Once you have a feel for the overall picture from this page, work through the Bash Dictionary in the order below for efficient learning.
| Step | Topic | Pages |
|---|---|---|
| 1 | Setup and basics | [Setup] Bash Environment ↓ Creating and Running .sh Files ↓ Shebang / chmod +x |
| 2 | File operation commands | ls ↓ cd / pwd ↓ cp / mv / rm ↓ mkdir / rmdir / touch |
| 3 | Variables, conditionals, and loops | Variable Definition and Reference ↓ if / elif / else ↓ for ↓ while / until |
| 4 | Functions and script techniques | Function Definition ↓ Function Arguments and Return Values ↓ Special Variables ↓ test / Conditionals |
| 5 | Pipes and redirection | Pipe ↓ Redirection (Output) ↓ Redirection (Input) / Here Document |
| 6 | Text processing | grep ↓ sed ↓ awk ↓ wc / sort / uniq |
| 7 | File and process management | find ↓ head / tail ↓ ps / top / htop ↓ kill / pkill / killall |
| 8 | Automation and advanced use | crontab ↓ Background Jobs ↓ ssh / scp / rsync |
Summary
Bash = The standard shell for Unix-based systems (Bourne Again SHell)
Its role
- Acts as a bridge so users can send commands to the OS kernel
- Automates commands through scripting
- Combines tools with pipes and redirection
Bash's strengths
- Ships preinstalled on macOS and Linux — no setup required
- Well-suited for server administration and automating routine tasks
- Powerful integration with text-processing tools like grep, sed, and awk
Key behaviors to remember
- No spaces allowed around
=in variable assignment - Spaces are required inside
[ ]in conditionals - All values are essentially strings (no built-in type system)
- Scripts continue on error by default; use
set -eto stop on errors
Major features
- File operations:
ls/cd/cp/mv/rm - Variables, conditionals, loops, and functions
- Pipe
|and redirection>>>< - Text processing:
grep/sed/awk - Process management:
ps/kill/ background execution
What Bash Is Good For
- Automating file backups, moves, and organization
- Log monitoring, aggregation, and alerting
- Scheduled execution with cron
- Deployment scripts to servers
- Pipeline processing by combining multiple commands
When to Combine Bash with Other Languages
For large-scale business logic, complex data processing, or anything involving structured objects, scripting languages like Python, Ruby, or Perl are better suited. Bash handles "organizing files and running commands automatically" well, while a separate language fits "analyzing data and calling APIs (Application Programming Interface — an interface for software components to communicate)."
If you find any errors or copyright issues, please contact us.