Command Lists with ;, &&, and ||

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 65 of 205

A command list is a sequence of commands joined by ;, && or ||. These three operators decide whether the next command runs, and under what condition. They are the simplest form of flow control in Bash: you can run commands one after another, run a command only if the previous one succeeded, or run a command only if the previous one failed. They are the building blocks that later lessons on if statements and error handling extend.

Every example below depends on exit status. A command that succeeds returns 0, and a command that fails returns a non-zero value. The commands true and false do nothing except return 0 and 1, so they work well for demonstrations.

Understanding the Concept

When you type two commands on separate lines, Bash runs the first, then the second. The operators in this lesson let you put several commands on one line and add a rule about the exit status:

OperatorMeaning
a ; bRun a, then run b, whatever happened to a.
a && bRun b only if a succeeded (status 0).
a || bRun b only if a failed (non-zero status).

The && operator reads as "and then" and || reads as "or else".

Running Commands in Sequence with ;

The semicolon separates commands that run one after another. It is equivalent to a newline:

echo one; echo two; false; echo three

Output:

one
two
three

Even though false failed, echo three still ran. The semicolon does not look at the exit status. A newline in a script does the same thing, so these two lines are identical to the one above:

echo a
echo b
a
b

Running the Next Command Only on Success with &&

The && operator runs the second command only if the first one returned status 0:

true && echo "ran after success"
false && echo "should not print"
echo "status after false &&: $?"

Output:

ran after success
status after false &&: 1

The second echo never ran, and the status of the whole list is the status of the last command that was executed, which was false, so $? is 1.

This is the right tool when later steps depend on earlier ones. For example, change into a directory only if it was created:

mkdir proj && cd proj && pwd

If mkdir failed, for example because the directory already existed or the path was not writable, the cd and pwd would be skipped, and the shell would not end up in a wrong place. Using ; here would run cd regardless.

Running the Next Command Only on Failure with ||

The || operator runs the second command only if the first one failed:

false || echo "ran after failure"
true || echo "should not print"
echo "status after true ||: $?"

Output:

ran after failure
status after true ||: 0

This is the usual form for fallbacks and error messages:

ls nofile 2>/dev/null || echo "no such file"

Output:

no such file

Here the error message of ls was discarded, and the list printed its own message because ls failed.

A tidy way to create a file only when it is missing combines a test with the two operators:

[ -f nofile ] || echo "creating"; touch nofile
[ -f nofile ] && echo "exists now"

Output:

creating
exists now

The [ -f nofile ] command tests whether a regular file with that name exists. Lessons 68 and 71 cover the [ command and file tests in detail.

The Exit Status of a List

The status of a list is the status of the last command that actually ran. The four cases:

true && false; echo "status: $?"
false || true; echo "status: $?"
false && true; echo "status: $?"
true || false; echo "status: $?"

Output:

status: 1
status: 0
status: 1
status: 0

In the third and fourth lines, the second command was skipped, so the status came from the first command.

Combining && and || in One List

The operators && and || have equal precedence, and Bash evaluates the list from left to right. Each operator looks at the status of whatever ran last. Watch what these four lists print:

false || echo A && echo B
true || echo A && echo B
false && echo A || echo B
true && echo A || echo B

Output:

A
B
B
B
A

Follow the first line step by step: false fails, so || runs echo A, which succeeds, so && echo B runs as well, and both letters appear. In the second line, true succeeds, so || echo A is skipped. The list status is still 0 from true, so && echo B runs. Only B is printed. The third line prints only B, and the fourth prints only A.

The A && B || C Pattern Is Not if/else

It is tempting to read A && B || C as "if A, then B, else C". That reading is wrong when B can fail, because C then runs after a successful A:

true && false || echo "C ran even though A succeeded"

Output:

C ran even though A succeeded

The same happens with a command that does real work and fails at the end:

r() { true && { echo "B ran"; false; } || echo "C also ran"; }
r

Output:

B ran
C also ran

When a real choice between two branches is needed, an if statement is clearer and correct:

if true; then echo "B"; else echo "C"; fi
B

Lesson 66 introduces if in full. The list form is best kept for short, single-purpose checks.

Grouping Commands

To make the right-hand side of && or || run several commands, group them. Curly braces run the group in the current shell, and each command inside must end with a semicolon or a newline, with a space after the opening brace:

false && { echo X; echo Y; } || { echo "fail path 1"; echo "fail path 2"; }

Output:

fail path 1
fail path 2

Parentheses run the group in a subshell, which means changes such as cd or variable assignments do not leak out:

( cd /tmp && pwd ); pwd

The first pwd printed /tmp from inside the subshell, and the second printed the directory the shell was in before.

Practical Applications

The following examples show how scripts typically use lists.

Check that a tool is installed before using it:

command -v bash > /dev/null && echo "bash found"
command -v nosuchtool > /dev/null || echo "nosuchtool missing"

Output:

bash found
nosuchtool missing

The command command -v name prints where the command was found and returns 0, or returns non-zero if it does not exist. Output is sent to /dev/null, so only the status matters.

Create a missing file, then act on it:

f=data.txt
[[ -e $f ]] || { echo "missing $f"; }
printf 'x\n' > $f
[[ -s $f ]] && echo "$f has content"

Output:

missing data.txt
data.txt has content

Use grep -q to choose between branches:

echo "hello" | grep -q hell && echo "matched"
echo "hello" | grep -q xyz || echo "no match"

Output:

matched
no match

Stop a script when something is wrong. The following script changes directory or exits with status 3:

cd /nonexistent 2>/dev/null || { echo "cannot cd" >&2; exit 3; }
echo "not reached"

Output when saved as ex.sh and run with bash ex.sh; echo "status: $?":

cannot cd
status: 3

The message went to standard error, and the exit inside the braces ended the whole script. Lesson 118 covers exit in detail.

A helper function with || makes an error message short:

die() { echo "error: $*" >&2; return 1; }
[ -d /nonexistent ] || die "missing directory"
echo "status: $?"

Output:

error: missing directory
status: 1

Lists and Pipelines Together

A pipeline binds more tightly than && and ||. The status that the list sees is the status of the whole pipeline, which by default is the status of the last command in it:

echo "a b c" | wc -w && echo "ok"
false | true || echo "not printed because last cmd succeeded"
true | false || echo "printed because last cmd failed"

Output:

3
ok
printed because last cmd failed

The second line printed nothing because true ended the pipeline with status 0, as lesson 61 explained.

Lists with set -e

With set -e, a script stops when a command fails, but not when the failing command is part of a && or || list, except for the last command of the list. The next script shows both cases:

set -e
false || echo "handled"
echo "still running"
false && echo "no"
echo "reached after false &&"
true && false
echo "NOT reached"

Output when run as a script, followed by its status:

handled
still running
reached after false &&
e.sh status: 1

Three different outcomes appear. The first false is followed by ||, so the failure was handled and the script went on. The second false was followed by &&, so its failure was tolerated and the script went on, too. But in true && false, the failing command is the last in the list, so set -e ended the script, and the final echo never ran. Lesson 119 discusses these rules in depth.

To ignore a failure on purpose in a script that uses set -e, end the command with || true:

set -e
grep -q nomatch /etc/hostname || true
echo "script continues"

Output:

script continues

Line Continuation After && and ||

When a line ends with && or ||, Bash expects the list to continue on the next line, so long lists can be split:

true &&
  echo "continued after &&"
false ||
  echo "continued after ||"

Output:

continued after &&
continued after ||

An operator at the start of a line is an error:

&& echo b

Output:

bash: -c: line 1: syntax error near unexpected token `&&'
bash: -c: line 1: `&& echo b'

A double semicolon is also an error outside a case statement:

echo a;; echo b

Output:

bash: -c: line 1: syntax error near unexpected token `;;'
bash: -c: line 1: `echo a;; echo b'

The ;; token has a special meaning inside case, which lesson 75 covers.

Running a Command in the Background with &

The ampersand & is a related operator that ends a command and starts it in the background, so the shell does not wait for it. It is covered in the lessons on processes (135 and 136). A short preview:

sleep 0.1 & echo "started background"; wait
echo "after wait"

Output:

started background
after wait

The command wait made the shell pause until the background job ended.

Portability

The operators ;, && and || are part of the POSIX standard and work in Dash:

dash -c 'false || echo dash-or; true && echo dash-and'

Output:

dash-or
dash-and

The next lessons move from running commands in order to making decisions with them, beginning with the if statement.

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 Command Lists with ;, &&, and || and get answers drawn from it.

Signed-in readers only.