Shell Operators
Command Chaining
Section titled “Command Chaining”| Operator | Name | Behavior |
|---|---|---|
A ; B | Semicolon | Run B after A regardless of A’s exit status |
A && B | AND | Run B only if A succeeds (exit code 0) |
A || B | OR | Run B only if A fails (non-zero exit code) |
A | B | Pipe | Send A’s stdout as B’s stdin |
# Always run bothmkdir /tmp/work ; cd /tmp/work
# Only continue if previous succeedsapt update && apt upgrade -y
# Fallback on failureping -c1 host1 || ping -c1 host2
# Chain with both./build.sh && echo "Success" || echo "Failed"Output Redirection
Section titled “Output Redirection”| Operator | Purpose |
|---|---|
> | Redirect stdout to file (overwrite) |
>> | Redirect stdout to file (append) |
2> | Redirect stderr to file |
2>> | Redirect stderr to file (append) |
&> | Redirect both stdout and stderr to file |
2>&1 | Redirect stderr to wherever stdout is going |
< file | Use file as stdin |
# Save command output to fileecho "hello" > output.txt
# Append to a logecho "entry" >> log.txt
# Discard errorsfind / -name "*.conf" 2>/dev/null
# Capture everything./script.sh &> all-output.txt
# Redirect stderr to stdout then pipe both./script.sh 2>&1 | grep "error"Background & Job Control
Section titled “Background & Job Control”| Operator | Purpose |
|---|---|
& | Run command in background |
Ctrl+Z | Suspend foreground job |
bg | Resume suspended job in background |
fg | Bring background job to foreground |
jobs | List background jobs |
nohup | Run command immune to hangups (survives logout) |
disown | Detach a running job from the shell |
# Run in background./long-task.sh &
# Check background jobsjobs -l
# Survive logoutnohup ./server.sh &Subshells & Grouping
Section titled “Subshells & Grouping”| Syntax | Purpose |
|---|---|
(A; B) | Run A and B in a subshell (own environment) |
{ A; B; } | Run A and B in the current shell (grouped) |
$(command) | Command substitution — capture output |
`command` | Command substitution (legacy syntax) |
# Subshell — cd doesn't affect parent(cd /tmp && ls)
# Grouping — redirect output of multiple commands{ echo "header"; cat data.txt; } > combined.txt
# Command substitutionfiles=$(ls *.txt)echo "Today is $(date +%Y-%m-%d)"Test & Conditional
Section titled “Test & Conditional”| Syntax | Purpose |
|---|---|
[[ condition ]] | Bash conditional test |
$? | Exit code of last command (0 = success) |
test expression | POSIX conditional test |
# Check if file exists[[ -f /etc/passwd ]] && echo "exists"
# Check exit codegrep -q "root" /etc/passwdecho $? # 0 if found, 1 if not
# String comparison[[ "$USER" == "root" ]] && echo "running as root"Special Variables
Section titled “Special Variables”| Variable | Meaning |
|---|---|
$? | Exit code of last command |
$$ | Current shell’s PID |
$! | PID of last background command |
$0 | Name of the script |
$1–$9 | Positional arguments |
$# | Number of arguments |
$@ | All arguments (as separate words) |
$* | All arguments (as one word) |