π§ 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"
- 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").
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="-------------------------"
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.
Argument | Description |
---|---|
VAR | Variable(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.
Argument | Description |
---|---|
VAR | Variable(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