Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Linux & Mac & Bash Command Dictionary

  1. Home
  2. Linux & Mac & Bash Command Dictionary
  3. Beginners Guide: Overview, Features, and Learning Path

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
RoleThe "screen" that displays text and accepts inputThe "processing engine" that interprets and runs commands
ExamplesmacOS Terminal.app, iTerm2bash, 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.

User Terminal (screen) Bash (shell) OS

Bash's Characteristics and Trade-offs

What Bash Does Well

FeatureDetails
Comes preinstalledAvailable on macOS and Linux with no installation needed; practically guaranteed on server environments
Pipes and redirectionCombine commands to express complex operations in a single line
ScriptingAutomate repetitive tasks; combine with cron for scheduled execution
Text processingPowerful integration with tools like grep, sed, and awk
Long historyIn use since 1989; rich documentation and community resources

Where Bash Can Be Awkward

AspectDetails
Unique syntaxRules differ from languages like Python or PHP — for example, spaces around = change the meaning
Error handlingScripts continue running even when a command fails by default; set -e changes this behavior
No typesAll values are essentially strings; arithmetic requires special notation
Complex logicFor large-scale logic, alternatives such as Python or Ruby are an option
PortabilityBash-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.

Terminal Command input/output screen Bash (shell) Interprets commands, expands variables, pipes Kernel (OS core) Executes system calls, file I/O, process management Hardware / File system

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.

CommandDescriptionCommon Example
lsList files in a directoryls -la (detailed list including hidden files)
cdChange directorycd /var/log
pwdPrint working directorypwd
cpCopy files or directoriescp file.txt backup.txt
mvMove or renamemv old.txt new.txt
rmDelete files or directoriesrm -rf dir/ (recursive; use with caution)
mkdirCreate a directorymkdir -p a/b/c (create intermediate directories too)
touchCreate an empty file or update timestamptouch 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

OperatorMeaningExample
-eqEqual to[ $a -eq $b ]
-neNot equal to[ $a -ne $b ]
-gtGreater than[ $a -gt 10 ]
-ltLess than[ $a -lt 10 ]
-geGreater than or equal to[ $a -ge 10 ]
-leLess than or equal to[ $a -le 10 ]
=Strings are equal[ "$str" = "hello" ]
!=Strings are not equal[ "$str" != "hello" ]
-zString is empty[ -z "$str" ]
-fFile exists[ -f "/etc/hosts" ]
-dDirectory 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

SymbolMeaningExample
>Write stdout to a file (overwrite)echo "hello" > out.txt
>>Append stdout to a fileecho "world" >> out.txt
<Read a file as stdinsort < list.txt
2>Write stderr to a filecmd 2> err.log
&>Write both stdout and stderr to a filecmd &> 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.

CommandDescription
catDisplay the full contents of a file
headDisplay the first N lines of a file (default: 10)
tailDisplay the last N lines; -f follows new output in real time
lessBrowse a file page by page (good for large files)
wcCount lines, words, and bytes
sortSort lines
uniqRemove consecutive duplicate lines (pairs well with sort)
findSearch for files matching given criteria
tarArchive, 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.

CommandDescription
psList running processes
topShow CPU (Central Processing Unit — the processor that executes computations) and memory usage in real time
killTerminate a process by its PID (process ID)
pkillTerminate 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

TypeSyntaxDescription
Single-line comment# textEverything from # to the end of the line becomes a comment. Also used as an inline note after code.
Shebang#!/usr/bin/env bashA 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.

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 -e to 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 .