How to Use Ternary Operator
Quick Answer: Ternary-Like Operators in Bash
Bash doesn’t have a native ternary operator, but you can use [ condition ] && true_value || false_value for simple cases, or better yet, arithmetic expansion: result=$(( condition ? value1 : value2 )). The second approach is safer because it doesn’t fail if the true value is falsy.
Quick Comparison: Conditional Assignment Methods
| Method | Syntax | Best For | Risk |
|---|---|---|---|
| Arithmetic ternary | $(( cond ? yes : no )) | Numeric values | None - safe |
| && and || | [ cond ] && yes || no | Simple conditions | Fails if true_value is falsy |
| if-then-else | if [ cond ]; then yes; else no; fi | Any case | None - most explicit |
| Parameter expansion | ${var:+yes}${var:-no} | Default values | None - focused |
Bottom line: Use arithmetic ternary $(( condition ? 1 : 0 )) for numeric logic and if-then-else for everything else. Avoid && and || chains unless you’re sure the true value won’t fail.
Ternary-Like Operators in Bash
Bash doesn’t have a true ternary operator like condition ? true_value : false_value in C-style languages, but it offers several ways to achieve the same concise conditional logic. These techniques let you write cleaner, more readable one-liners.
Method 1: Using && and || Operators
The most common approach chains logical operators:
#!/bin/bash
# Basic pattern: condition && true_action || false_action
age=20
[ $age -ge 18 ] && echo "Adult" || echo "Minor"
# Output: Adult
# Assign result to variable
status=
[ $age -ge 18 ] && status="Adult" || status="Minor"
echo "Status: $status"
When to Use && and ||
- You have simple boolean conditions
- The true value won’t fail (is a simple echo or command that always succeeds)
- You’re writing a quick one-liner
- You understand the risks and handle them
Method 2: Using Conditional Substitution
This is more explicit and avoids edge cases:
#!/bin/bash
# Using if-then-else in command substitution
age=20
status=$(if [ $age -ge 18 ]; then echo "Adult"; else echo "Minor"; fi)
echo "Status: $status"
When to Use Conditional Substitution
- You want explicit, safe code
- The condition might fail or be complex
- You’re writing production code
- You need to ensure both branches are safe
Method 3: Using Parameter Expansion
Modern Bash parameter expansion can provide ternary-like behavior:
#!/bin/bash
# Pattern: ${variable:+true_value}${variable:-false_value}
user="john"
message="${user:+Hello $user}${user:- No user}"
echo "$message"
# Output: Hello john
# Empty user
user=""
message="${user:+Hello $user}${user:-No user}"
echo "$message"
# Output: No user
When to Use Parameter Expansion
- You’re checking if a variable is set or empty
- You want efficient, built-in expansion
- You’re setting default values
- You need to test variable existence
Practical Examples
Format Output
#!/bin/bash
# Simple ternary for formatting
count=5
echo "You have $([ $count -eq 1 ] && echo "1 file" || echo "$count files")"
# Output: You have 5 files
# With count=1
count=1
echo "You have $([ $count -eq 1 ] && echo "1 file" || echo "$count files")"
# Output: You have 1 file
Conditional Variable Setting
#!/bin/bash
# Set variable based on condition
debug_mode=$1
debug_flag=$([ "$debug_mode" = "true" ] && echo "-v" || echo "")
echo "Debug flag: $debug_flag"
# Use in command
find . $debug_flag # May or may not include -v
Method 4: Using Arithmetic Expansion
For numeric conditions:
#!/bin/bash
num=10
# Ternary-like in arithmetic context
result=$(( num > 5 ? 100 : 50 ))
echo "Result: $result"
# Output: Result: 100
# Nested ternary
grade=85
letter=$(( grade >= 90 ? 65 : grade >= 80 ? 66 : grade >= 70 ? 67 : 68 ))
# 65='A', 66='B', 67='C', 68='D'
When to Use Arithmetic Expansion
- You’re working with numeric values
- You need a safe, true ternary behavior
- You’re doing math-based conditionals
- You want code that won’t have edge case failures
Conditional File Paths
#!/bin/bash
# Set path based on condition
env=$1
config_file=$([ "$env" = "prod" ] && echo "/etc/app/prod.conf" || echo "/etc/app/dev.conf")
echo "Using config: $config_file"
Conditional Command Execution
#!/bin/bash
# Run different command based on condition
backup_dir="/backups"
# Create backup directory if it doesn't exist and report
[ ! -d "$backup_dir" ] && mkdir -p "$backup_dir" && echo "Created backup dir" || echo "Backup dir exists"
Ternary in Array Operations
#!/bin/bash
# Choose array based on condition
env="prod"
declare -a prod_servers=("server1" "server2")
declare -a dev_servers=("localhost")
# Select array
[ "$env" = "prod" ] && servers=("${prod_servers[@]}") || servers=("${dev_servers[@]}")
echo "Servers: ${servers[@]}"
Important Caveats
The && || pattern has one gotcha:
#!/bin/bash
# PROBLEM: If true_action fails, false_action still runs
false && echo "True" || echo "False"
# Output: False <- This is misleading!
# SOLUTION: Use if-then-else or check exit codes carefully
if false; then
echo "True"
else
echo "False"
fi
# Output: False <- Correct
Safer Conditional Assignment
#!/bin/bash
# Instead of: [ condition ] && var="yes" || var="no"
# Use this pattern:
condition=true
# Explicit and safe
if $condition; then
result="yes"
else
result="no"
fi
echo "$result"
Default Values
#!/bin/bash
# Use parameter expansion for defaults
username="${1:-root}" # Default to 'root' if not provided
port="${2:-8080}" # Default to 8080 if not provided
echo "User: $username, Port: $port"
Quick Reference
#!/bin/bash
value=5
# Method 1: && ||
result=$([ $value -gt 0 ] && echo "positive" || echo "not positive")
# Method 2: if-then-else
result=$(if [ $value -gt 0 ]; then echo "positive"; else echo "not positive"; fi)
# Method 3: arithmetic ternary
result=$(( value > 0 ? 1 : 0 ))
# Method 4: case statement
case $value in
[1-9]) result="positive" ;;
*) result="not positive" ;;
esac
echo "$result"
Comparing different approaches:
- Arithmetic ternary: Safest for numeric logic, never fails
- if-then-else: Most explicit, works for any condition
- && and ||: Quickest for simple cases, but risky
- Parameter expansion: Efficient for variable defaults
Quick Reference
# Numeric ternary (SAFE)
result=$(( condition ? 1 : 0 ))
# Simple with && || (RISKY - use only for safe true_value)
result=$([ condition ] && echo "yes" || echo "no")
# Explicit if-then-else (SAFE - always works)
result=$(if [ condition ]; then echo "yes"; else echo "no"; fi)
# Default values (SAFE)
var=${1:-default}
# Check if variable exists
message="${var:+Value is: $var}${var:-Variable is empty}"
Summary
While Bash lacks a true ternary operator, you can achieve similar concise conditional logic using && and ||, arithmetic expansion, or parameter expansion. For reliability, prefer explicit if-then-else statements, especially in production code. Reserve ternary-like patterns for simple, safe conditions.