Using Semicolons and Newlines

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 33 of 205

Bash has to know where one command ends and the next begins. It uses two main separators for this: the newline and the semicolon. They are interchangeable in most places, and understanding exactly how they work explains many of the syntax errors beginners meet.

Commands Are Separated by Newlines or Semicolons

A newline ends a command, so the usual way to write a script is one command per line:

echo one
echo two

A semicolon does the same job within a line, so several commands can share a line:

echo one; echo two; echo three
one
two
three

The two forms are equivalent. Bash runs the commands in order, and each command starts only after the previous one has finished. The exit status of the whole line is the status of the last command, so true; false; echo "status=$?" prints status=1: only the final status survives, and earlier failures are not reported.

A semicolon is not needed at the end of the last command on a line, because the newline already ends it. A trailing comment after a semicolon is fine as well:

echo hi; # this comment is ignored
echo there
hi
there

A Semicolon Always Continues

The semicolon runs the next command no matter what happened before it:

ls /nonexistent_dir 2>/dev/null; echo "after the semicolon"
after the semicolon

The first command failed, but the second still ran. If you want the second command to run only when the first succeeds, use && instead; to run it only when the first fails, use ||. Both of these are explained in a later lesson on command lists, but a short preview shows the contrast:

ls /nonexistent_dir 2>/dev/null && echo "after &&"; echo "end"
end

The echo "after &&" was skipped because ls failed. The semicolon after it then started a fresh command, which ran as usual.

The same pair can create a safe "if this works" chain:

mkdir -p d33 && cd d33 && pwd

Each step runs only if the one before it worked, and the whole chain stops at the first failure.

Semicolons in Compound Commands

Commands such as if, for, and while have several parts, and the parts must be separated. On separate lines, the newline does this automatically:

if [ 1 -eq 1 ]
then
  echo "newline style"
fi
newline style

To write the same thing on one line, use a semicolon where the newline was. Here the semicolon after the test [ 3 -gt 2 ] marks the end of the condition so that then can begin:

if [ 3 -gt 2 ]; then echo bigger; fi
bigger

Loops follow the same rule. The keyword do must start a new command, so it needs either a newline or a semicolon before it:

for n in 1 2 3; do echo "n=$n"; done
n=1
n=2
n=3

The multi-line form is more common in scripts because it is easier to read:

i=0
while [ "$i" -lt 2 ]
do
  echo "i=$i"
  i=$((i + 1))
done
i=0
i=1

Most people put then and do at the end of the first line, after a semicolon, so the keyword and its condition stay together:

for f in a b; do
  echo "$f"
done

What Happens When a Separator Is Missing

If the semicolon or newline is left out, Bash reads the keyword as an ordinary word belonging to the previous command, and then it hits something it does not expect. Leaving the semicolon out of an if produces:

if [ 3 -gt 2 ] then echo bigger; fi
syntax error near unexpected token `fi'

Bash read then, echo, and bigger as extra arguments to the [ command, never saw a real then, and complained at fi. The same thing happens with a loop:

for n in 1 2 3 do echo $n; done
syntax error near unexpected token `done'

Here do and the words after it became part of the list of values after in, so the loop never received its do. The exact wording and line numbers of these messages depend on the Bash version and on whether the script is run from a file, but the missing separator is always the cause. When you see "unexpected token", check the line just before the token it names.

Grouping Commands

Curly braces group several commands so that they act as one. The rules are strict: the opening brace must be followed by a space, and the last command inside must end with a semicolon or newline before the closing brace.

{ echo a; echo b; }
a
b

Without the semicolon after echo b, Bash treats } as an ordinary argument to echo and keeps waiting for the real closing brace:

{ echo a; echo b }
syntax error: unexpected end of file

Parentheses create a subshell, which runs the group in a separate child copy of the shell. They do not need the same spacing, and a change such as cd inside them does not affect the surrounding script:

(cd /tmp; pwd)
pwd
/tmp
/home/user/project

The second line shows the original directory, which will be whatever directory you ran the script from. The cd happened only inside the subshell.

The Double Semicolon in case

Inside a case statement, two semicolons (;;) end the commands belonging to one pattern. It is a different symbol with a different meaning, and it is not allowed anywhere else:

x=b
case $x in
  a) echo A ;;
  b) echo B ;;
  *) echo other ;;
esac
B

The same case can be written on a single line, as in case $x in a) echo A ;; b) echo B ;; *) echo other ;; esac. Placing ;; outside a case is a syntax error:

echo a;; echo b
syntax error near unexpected token `;;'

Likewise, a semicolon cannot start a line or follow another separator directly, because Bash does not allow an empty command in front of it:

; echo x
syntax error near unexpected token `;'

Running a Command in the Background

The ampersand (&) also ends a command, but it starts the command in the background instead of waiting for it. The next command begins immediately:

sleep 0.2 & echo started; wait; echo finished
started
finished

echo started ran while sleep was still going. The wait command then paused the script until the background job ended. Background jobs are the subject of a later lesson, so this is only a short look at how & differs from ;.

Splitting a Long Command Across Lines

A long command can be spread over several lines in two ways.

With a backslash at the end of the line. The backslash cancels the newline that follows it, so Bash sees one long line. Nothing, not even a space, may come after the backslash:

echo "one" \
  "two" \
  "three"
one two three

After an operator that needs more input. If a line ends with |, &&, or ||, Bash knows the command is not finished and continues on the next line without a backslash:

printf 'b\na\n' |
  sort
echo a &&
  echo b
a
b
a
b

The operator must be at the end of the first line. Starting the second line with it is an error, because the first line was already a complete command:

echo a
| cat
a
syntax error near unexpected token `|'

Note that a was printed before the error, because Bash ran the complete first line as soon as it read it.

Newlines and Semicolons Inside Quotes

Inside quotes, both characters are ordinary text. A quoted string can contain a real newline, and Bash includes it in the string:

echo "line1
line2"
line1
line2

A quoted semicolon is just a character, and it does not separate commands:

echo 'a; b'
a; b

The same is true of an unquoted semicolon that is escaped with a backslash. This is useful when you pass a semicolon as an argument to another program, such as the -exec action of the find command, which requires one.

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 Using Semicolons and Newlines and get answers drawn from it.

Signed-in readers only.