Bash Scripting - Handling Defaults

Persistent vs. Temporary

${var:=default} — The Persistent Assignment

Logic: If $var is empty or unset, set $var to default and then return that value.

Example:

ubuntu in 🌐 cato in ~
❯ echo $name


ubuntu in 🌐 cato in ~
❯ echo "${name:=User}"
User

ubuntu in 🌐 cato in ~
❯ echo $name
User
  1. name="" (name is empty)
  2. echo “${name:=User}”
    • Bash sees name is empty.
    • It assigns “User” to the variable name
    • It then prints “User”.
  3. echo $name now prints “User” because the variable was actually changed.Bash

Note: The = stands for equal, as in “Make the variable equal to this from now on.


${var:-default} — The Temporary Fallback

Logic: If $var is empty or unset, use default just for this command, but do not change the original variable.

Example:

ubuntu in 🌐 cato in ~
❯ name=""

ubuntu in 🌐 cato in ~
❯ echo "Hello, ${name:-User}"
Hello, User

ubuntu in 🌐 cato in ~
❯ echo $name
  1. name=”" (name is empty)
  2. echo “Hello, ${name:-User}”
    • Bash sees name is empty.
    • It provides “User” to the echo command.
    • It does not touch the variable name.
  3. echo $name returns nothing (empty) because the expansion was “read-only.”

Note: The - is like a dash in and out. It provides the value and leaves.


The Patterns

Syntax Meaning
${var:-default} Use default if var is empty/unset (var unchanged)
${var:=default} Set var to default if empty/unset (var updated)
${var:?error} Exit with error message if var is empty/unset

my DevOps Odyssey

“Σα βγεις στον πηγαιμό για την Ιθάκη, να εύχεσαι να ‘ναι μακρύς ο δρόμος, γεμάτος περιπέτειες, γεμάτος γνώσεις.” - Kavafis’ Ithaka.