Combining Commands
Beyond pipes, Linux provides several ways to combine and control command execution.
Command Separators
| Operator | Meaning | Example |
|---|---|---|
; | Run sequentially | cmd1 ; cmd2 |
&& | Run if previous succeeds | cmd1 && cmd2 |
| ` | ` | |
& | Run in background | cmd & |
Sequential Execution: ;
Run commands one after another:
echo "Starting" ; date ; echo "Done"
The second command runs regardless of whether the first succeeds.
Conditional AND: &&
Run second command only if first succeeds:
mkdir newdir && cd newdir
If mkdir fails, cd won't run (preventing errors).
Conditional OR: ||
Run second command only if first fails:
cd /nonexistent || echo "Directory not found"
Exercise: Use Conditional Execution
Create a directory and show a success message:
Combining && and ||
Create success/failure handlers:
command && echo "Success" || echo "Failed"
Background Execution: &
Run a command in the background:
long_running_command &
The shell returns immediately while the command runs.
Common Patterns
Safe Directory Creation
mkdir -p dir && cd dir
Compile and Run
gcc program.c -o program && ./program
Test and Deploy
npm test && npm run build && npm run deploy
Default Values
cd "$DIR" || cd /tmp
Create If Not Exists
[ -d "backup" ] || mkdir backup
Grouping Commands
Subshell: ()
Commands run in a subshell:
(cd /tmp && ls) # Changes dir only in subshell
pwd # Still in original directory
Current Shell:
Commands run in current shell:
{ cd /tmp && ls; }
pwd # Now in /tmp
Practical Examples
Backup and Verify
cp file.txt backup/ && ls backup/file.txt && echo "Backup complete"
Update System
apt update && apt upgrade -y
Install Dependencies
npm install || yarn install || echo "Install failed"
Exercise: Chain Commands
Run multiple commands that depend on each other:
Summary Table
| Pattern | Use Case |
|---|---|
cmd1 ; cmd2 | Always run both |
cmd1 && cmd2 | Run cmd2 if cmd1 succeeds |
| `cmd1 | |
cmd & | Run in background |
(cmd1; cmd2) | Run in subshell |
Key Takeaways
;runs commands sequentially regardless of success&&runs next command only if previous succeeds||runs next command only if previous fails- Combine
&&and||for success/failure handling - Use
&to run commands in the background

