Default Values in Shell

Level 4121 keystrokes

${var:-default} supplies a default value when a variable is unset or empty, and ${var:?message} stops the script with an error in that case. The output assumes no arguments, PORT unset and HOME=/home/user.

Shell code

# Use the first argument, or "Guest" if it is missing or empty
1name=${1:-"Guest"}
# Same for an environment variable: 8080 unless PORT is set
2port=${PORT:-8080}
# :? prints the message and exits if HOME is unset or empty
3dir=${HOME:?"HOME not set"}
# Print the resulting values
4echo "User: $name"
5echo "Port: $port"
6echo "Home: $dir"

Output

User: Guest
Port: 8080
Home: /home/user
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 10
  • :× 6
  • $× 6
  • {× 3
  • }× 3
  • =× 3
  • -× 2
  • ?× 1

More Shell examples at level 4

← Shell typing practice