If else

3 snippets across 3 stacks - Bash & Linux, JavaScript, Python

SHBash & Linux

If / Else Conditional

SH · Bash Scripting
Syntax
if [[ condition ]]; then
  commands
elif [[ condition ]]; then
  commands
else
  commands
fi
Example
if [[ -f "/opt/app/config.yml" ]]; then
  echo "Config found"
elif [[ -f "/etc/app/config.yml" ]]; then
  echo "Using system config"
else
  echo "No config found, using defaults"
  exit 1
fi

Note Use [[ ]] (double bracket) over [ ] for safer string comparisons and pattern matching. Common file tests: -f (file exists), -d (directory exists), -r (readable), -z (string is empty), -n (string is not empty). Use && and || inside [[ ]].

JSJavaScript

if / else if / else

JS · Control Flow
Syntax
if (condition) { ... }
else if (condition) { ... }
else { ... }
Example
function getDiscount(memberLevel) {
  if (memberLevel === "gold") {
    return 0.20;
  } else if (memberLevel === "silver") {
    return 0.10;
  } else {
    return 0;
  }
}
console.log(getDiscount("gold")); // 0.20

Note Conditions are coerced to boolean. Watch out for truthy/falsy gotchas: if (arr.length) works because 0 is falsy.

PYPython

if / elif / else

PY · Control Flow
Syntax
if condition:
    ...
elif condition:
    ...
else:
    ...
Example
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(grade)
Output
B

Note Python uses indentation instead of braces. There is no switch statement in older Python; use match/case (3.10+) for pattern matching.

Frequently asked questions

How does Bash & Linux handle if else?
This task is covered in 3 stacks on this page: Bash & Linux, JavaScript, Python. The "If / Else Conditional" snippet in Bash & Linux uses `if [[ condition ]]; then`.
Which command does the Bash & Linux example use?
The "If / Else Conditional" snippet uses `if [[ condition ]]; then`, from the Bash Scripting section of the Bash & Linux cheat sheet.
Which stacks cover "if else" on this page?
Bash & Linux, JavaScript, Python. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "If / Else Conditional": Use [[ ]] (double bracket) over [ ] for safer string comparisons and pattern matching. Common file tests: -f (file exists), -d (directory exists), -r (readable), -z (string is empty), -n (string is not empty). Use && and || inside [[ ]].