Skip to main content

πŸ”§ Variables

Variables let you store and reuse information. This guide covers how to create variables, use their values, and check if they exist.


Defining Variables​

To create a variable, use the = symbol with no spaces around it. Here's the basic syntax:

VARIABLE_NAME="VALUE"
note
  • Variable names are case-sensitive ("a" and "A" are distinct).
  • Names must start with an alphabetic character or "_" (e.g., "A", "__A"). Starting with numbers (e.g., "90", "90__MyVar") is invalid.
  • After the first character, names can include letters, numbers, or "_" (e.g., "MyVar__90").
warning

Avoid using variable names starting with ___ (three underscores). This prefix is reserved for provisional environment variables used internally by DI. Using it in your scripts may cause conflicts or data loss.

Examples​

a="Ole"
A="Just test"
A10="a b c d e"
_A="1 2 3 4 5"
B_="W e l c o m e !"
B_1_2_3="-------------------------"
tip

Always enclose the value in quotes (") to handle spaces or special characters safely.


Using Variables​

To use a variable’s value, add a $ before its name. This tells the script to replace $VARIABLE_NAME with its stored value.

Basic Usage​

greeting="Hello"
ui_print "$greeting everyone" # Prints "Hello everyone"

Avoiding Confusion with Braces​

If a variable is followed by text that could mix with its name, use ${} to clearly separate it:

name="Alice"
ui_print "$name123" # Tries to use "name123", not only "name"
ui_print "${name}123" # Prints "Alice123"

Checking If Variables Are Defined​

Sometimes you need to know if a variable has been created. Use defined to check if it exists, or undefined to check if it doesn’t.

defined​

Checks if one or more variables are set.

ArgumentDescription
VARVariable(s) to check (multiple allowed)
name="Alice"
if defined name; then
ui_print "Name is set"
fi

# Multiple variables
age="25"
if defined name age; then
ui_print "Both name and age are set"
fi

undefined​

Checks if one or more variables are not set.

ArgumentDescription
VARVariable(s) to check (multiple allowed)
if undefined score; then
ui_print "Score is not set"
fi

# Multiple variables
if undefined score level; then
ui_print "Score and level are not set"
fi

Practical Example​

user="Bob"
if defined user; then
ui_print "User is $user"
else
ui_print "No user defined"
fi

if undefined points; then
points="0" # Set a default value
ui_print "Points set to $points"
fi