LOGBOOK

HELP

Quiz Entry - updated: 2026.07.14

What are the command chaining operators in Bash?

Chain commands by exit code: ; always runs the next, && runs it only on success, \|\| only on failure, & runs in the background.

&& and || are the shell's inline if/else. Because they react to exit codes, cmd1 && cmd2 runs cmd2 only when cmd1 succeeded (exit 0), and cmd1 || cmd2 runs cmd2 only when cmd1 failed. This makes one-liners like "make the dir, and if that worked, enter it" trivial: mkdir d && cd d.

A subtle ordering trap with all three combined: cmd1 && cmd2 || cmd3 runs cmd3 if either cmd1 or cmd2 fails — it's not a clean if/else, so don't read it as one for non-trivial logic.

Operator Meaning Example
; Run sequentially (always) cmd1 ; cmd2
&& Run next if previous succeeded cmd1 && cmd2
|| Run next if previous failed cmd1 || cmd2
& Run in background cmd &

Examples:

# Sequential (both always run)
echo "first" ; echo "second"

# AND - second runs only if first succeeds
mkdir /tmp/test && cd /tmp/test

# OR - second runs only if first fails
cd /nonexistent || echo "Directory not found"

# Background
long_running_command &

# Combined
mkdir dir && cd dir || echo "Failed"

Practical examples:

# Update and upgrade (stop if update fails)
sudo apt update && sudo apt upgrade

# Create dir if it doesn't exist
[ -d /tmp/mydir ] || mkdir /tmp/mydir

From Quiz: LIOS / Bash Scripting and Automation | Updated: Jul 14, 2026