Branching

2 snippets across 2 stacks — Bash & Linux, JavaScript

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.