Bash Syntax

Understanding the basic structure of Bash commands

📝 What is Bash Syntax?

Bash syntax refers to the rules and structure for writing commands in the Bash shell. It includes commands, arguments, operators, and special characters that tell the system what actions to perform.


# Basic command syntax
echo "Hello, World!"

# Command with options
ls -la /home
                                    

Key Syntax Elements

⌨️

Commands

Basic instructions to execute

pwd
🔧

Options

Modify command behavior

ls -l -a
📋

Arguments

Data passed to commands

cat file.txt
🔗

Operators

Connect and control commands

cmd1 && cmd2

🔹 Basic Command Structure

Bash commands typically follow: command [options] [arguments]. The command is the program or built-in to execute. Options (flags) modify behavior, usually prefixed with - (short) or -- (long). Arguments are the targets, like filenames or values. For example, ls -l /home lists files in long format. Understanding this pattern helps you construct and deconstruct any command. Many commands also accept input from stdin and send output to stdout/stderr. Mastering this basic grammar is the first step to fluency in the shell environment.

# Basic structure: command [options] [arguments]

# Simple command
date

# Command with option
ls -l

# Command with option and argument
cat -n file.txt

# Multiple options and arguments
cp -r -v source/ destination/

Output:

Fri Jan 10 14:30:00 UTC 2025

🔹 Comments

Comments, starting with #, are non-executable text that explains the code. They are vital for documentation, making scripts understandable to others (or your future self). Use them to describe the script's purpose, explain complex sections, note assumptions, or temporarily disable code. Good commenting practice includes a header with author, date, and description, plus inline comments for non-obvious logic. While over-commenting is unnecessary, critical sections and workarounds deserve explanation. Comments transform a cryptic sequence of commands into a maintainable piece of software.

# This is a single-line comment
echo "Hello"  # Comment after command

# Comments can explain what code does
# They are ignored during execution

: '
This is a multi-line comment
You can write multiple lines
Between the quotes
'

Output:

Hello

🔹 Command Chaining

Chain commands with ;, &&, ||, and | to control execution flow. A semicolon (;) runs commands sequentially, regardless of success. && runs the next command only if the previous succeeded. || runs the next only on failure. The pipe (|) sends the output of one command as input to the next. For example, grep "error" log.txt && mail -s "Alert" [email protected]. These operators enable powerful one-liners and streamline script logic by embedding conditionals directly into the command sequence.

# Semicolon - run commands sequentially
echo "First"; echo "Second"

# AND operator - run if previous succeeds
mkdir newdir && cd newdir

# OR operator - run if previous fails
cat file.txt || echo "File not found"

# Pipe - pass output to next command
ls -l | grep ".txt"

Output:

First
Second

🔹 Quoting and Escaping

Quoting and escaping manage how Bash interprets special characters and whitespace. Single quotes (' ') preserve all characters literally. Double quotes (" ") allow variable ($var) and command ($(cmd)) expansion but protect most others. The backslash (\) escapes a single following character. For example, echo "$HOME" expands the variable, while echo '$HOME' prints the literal string. Proper use prevents errors with filenames containing spaces or special symbols and is crucial for writing robust, predictable scripts.

Quote Types:

  • Single quotes ('') - Preserve literal value of all characters
  • Double quotes ("") - Allow variable expansion
  • Backslash (\) - Escape single character
# Single quotes - literal text
echo 'Hello $USER'
# Output: Hello $USER

# Double quotes - variable expansion
echo "Hello $USER"
# Output: Hello john

# Escape character
echo "Price: \$100"
# Output: Price: $100

# Spaces in filenames
cat "my file.txt"

🔹 Redirection

Redirection operators control where command input comes from and output goes. > file redirects stdout to a file (overwrites). >> file appends stdout. 2> file redirects stderr. &> file redirects both stdout and stderr. < file uses a file as stdin. For example, ls > list.txt saves the directory listing. Pipes (|) are a form of redirection between commands. Mastering redirection is key to scripting—logging outputs, separating errors, feeding data into programs, and building pipelines.

# Output redirection - overwrite file
echo "Hello" > output.txt

# Append to file
echo "World" >> output.txt

# Input redirection
sort < names.txt

# Redirect errors
ls nonexistent 2> error.log

# Redirect both output and errors
command > output.txt 2>&1

File content (output.txt):

Hello
World

🔹 Special Characters

Bash assigns special meaning to characters like $, *, ?, >, |, &, ;, (, ), [, ], {, }. The dollar sign ($) expands variables. Asterisk (*) is a wildcard for globbing. Understanding these is essential to avoid syntax errors and use features effectively. For example, unquoted * expands to filenames, while quoted it's literal. Learning the role of each character—for expansion, redirection, control, or grouping—unlocks the full expressive power of the shell and allows you to write concise, powerful commands.

Common Special Characters:

  • $ - Variable prefix or command substitution
  • * - Wildcard matching any characters
  • ? - Wildcard matching single character
  • ~ - Home directory shortcut
  • | - Pipe output to another command
  • & - Run command in background
  • ; - Command separator
# Variable
name="Alice"
echo $name

# Wildcards
ls *.txt
ls file?.txt

# Home directory
cd ~/Documents

# Background process
sleep 10 &

🔹 Command Substitution

Command substitution in Bash allows you to capture and use the output of a command directly within your script. By wrapping a command in $(...) or backticks, you can store its result in a variable, making your scripts dynamic and responsive to real-time system data. This technique is essential for automating tasks that depend on current dates, file counts, system information, or command results. For example, current_date=$(date) stores today's date, enabling your script to log events or generate time-stamped reports automatically. Mastering command substitution enhances script flexibility and reduces hard-coded values.

# Using $() - preferred method
current_date=$(date +%Y-%m-%d)
echo "Today is $current_date"

# Using backticks - older method
files=`ls -1 | wc -l`
echo "Number of files: $files"

# Nested substitution
echo "You are in $(basename $(pwd))"

Output:

Today is 2025-01-10
Number of files: 5
You are in Documents

🧠 Test Your Knowledge

Which operator runs the second command only if the first succeeds?