Let us talk about variables. When you are learning to code in whichever language, variables will always be there.
In this tutorial, we will introduce you to the world of scripting using ZSH by learning everything there is to learn about variables. This tutorial includes the variable usage and common variable manipulation.
Variable Definition
In ZSH, variables are data storage units that allows us to store and manipulate the data within the lifetime of the script.
A common analogy is that they are like containers that allows us to store the information such as text, numbers, sequences, and more.
Variable Declaration
Before you can use a variable in a script. You need to ensure that you declared a variable.
Variable declaration refers to the process of specifying the name, the data type of the variable, and the initial value held by it.
In ZSH, we can declare a variable implicitly or explicitly. Explicit declaration requires that you define the data type that is stored by the variable while implicit declaration requires just the variable name. The interpreter can then infer the data type of the variable when in use.
The following shows the explicit and implicit declaration:
greet="Hello"
The first command denotes the explicit declaration, while the second command denotes the implicit declaration.
You can assign a value to a variable by simply using the “=” operator during declaration as follows:
We can also provide the default values for variables using the ${var:-default} syntax.
As mentioned, we can explicitly specify the type of variable using the “typeset” command.
typeset -a dbs=("MySQL" "PostgreSQL" "SQLite") # Array variable
Variable Naming Conventions
When naming the variables, you must adhere to the following rules to avoid the syntax error by the ZSH interpreter:
- The variable names should consist of letters, digits, and underscores.
- They should begin with a letter or an underscore.
- Avoid using special characters like “$”, “*”, or spaces in variable names.
Variable Types in ZSH
There are various types of variables supported by ZSH. Each variable type is used to store a specific type of data such as numbers, strings, arrays, etc.
1. String Variables
String variables are used to store the textual data. In ZSH, we enclose the string variables in single or double quotes as shown in the following:
var2='Hello, World!'
Both of the previous variables represent the valid string data types.
2. Integers
Integer variables, on the other hand, are used to store the numeric values. This type of values do not require you to enclose them in quotes. However, they must be numerical values.
3. Array Variables
Array variables are sequence type that are used to hold the lists of values. We declare an array using a pair of parentheses. Unlike strings and integers, arrays can store the mixed types such as strings and integers in the same value.
An example is as follows:
Variable Expansion
Variable expansion, also known as variable substitution, allows us to replace a variable’s name with its corresponding value within a string or command.
Variable expansion enables us to dynamically incorporate the contents of variables into the code. In ZSH scripting, the variable expansion is a way to access and use the values that are stored in variables.
1. Simple Variable Expansion
The most common type of variable expansion uses the “$” symbol to access the value of a variable.
An example is as follows:
2. Parameter Expansion
Parameter expansion allows for more complex variable operations as demonstrated in the following example:
substring=${name:0:3}
The first example gets the length of the string while the second gets the specified substring using indexing.
<h2>3. Arithmetic Expansion</h2>
Lastly, we have the arithmetic expansion which allows us to perform the arithmetic operations inside the double parentheses.
[cc lang="bash" width="100%" height="100%" escaped="true" theme="blackboard" nowrap="0"]x=5
y=3
res=$((x + y))
Variable Manipulation
Let us move to the next section where we learn about variable manipulation. Start with the most common variable manipulation
1. String Manipulation
ZSH provides numerous string manipulation capabilities such as string concatenation. An example of string concatenation is as follows:
The next string manipulation operation is string substitution:
2. Array Manipulation
Arrays are another area where you encounter performing various operations. In arrays, we have various storage and manipulation techniques such as:
Adding an element to an array:
Accessing the array elements:
Arithmetic Operations
You can perform various arithmetic operations on integers such as:
Adding values:
You can just replace the arithmetic sign to perform other operations such as subtraction, multiplication, and division.
Advanced Variable Techniques in ZSH
There are some advanced variable operations that you will only encounter in specific use cases.
For example, a conditional variable assignment allows us to conditionally assign the values based on conditions.
An example is as follows:
In this case, if the “debug_mode” contains a non-empty value, the mode is assigned with the value of “debug_mode”.
For example, if “debug_mode=true”, the mode is also set to “true”.
If the “debug_mode” is not defined or is empty, the mode is assigned with the default value which is “false”.
1. Variable Scope
Another feature that you might want to know about variables is the variable scope. The scope refers to which area the variable is accessible.
For example, if a variable is defined outside a loop, function, or conditional block, it is said to have a global scope and can be accessed through the entire script.
The next type of scope is a local scope which limits the accessibility of variables that are defined within a loop, function, or conditional block to only that block.
func() {
local local_var="I'm local"
}
The example demonstrates the global and local variable scopes.
2. Special Variables
We also have special variables provided to use by ZSH. These are variables that have special meaning when used in the ZSH shell.
They include the following:
To represent the script arguments, an example usage is as follows:
first_argument="$1"
argument_count="$#"
3. Variable Sanitization
When dealing with user input, it is good to sanitize the input to prevent the attack vectors such a code injections.
An example is as follows:
4. Debugging the Variable
You can use the “set –x” command to debug and trace the variable assignments and values.
There you have it!
Conclusion
In this tutorial, you encountered one of the most comprehensive tutorials on variables in ZSH. This tutorial covers everything from the declaration to debugging the variables and everything in between. This tutorial will surely take you to the next-level when it comes to scripting with ZSH.