In this tutorial, we will learn all about functions and subroutines. This will guide you into learning how to encapsulate a logic and improve the code reusability to make the code more readable and easier to maintain.
What Is ZSH Function or Subroutine?
In Zsh, a function, also known as a subroutine or a user-defined command, is a self-contained block of code that performs a specific task or a set of related tasks.
Function Definition
We can define a function in Zsh using the “function” keyword or the shorthand notation () and the name of the function.
The syntax is as follows:
In Zsh, you can define the functions using the “function” keyword or the shorthand notation ():
# Function body
}
We can also use the shorthand notation as follows:
# Function body
}
Both approaches are valid, and you can choose the one that suits your style. Functions should be defined before you call them in a script.
Function Parameters
Like all functions, we can provide the parameters to any function that is defined in Zsh. We can then access the parameter using the special variables: $1, $2, $3, and so on where $1 represents the first parameter, $2 represents the second parameter, and so forth.
An example is as follows:
echo "First: $1"
echo "Second: $2"
}
# Call the function with arguments
print_parameters "Hello" "World"
In the given example, we define a function called print_parameters() that takes two parameters and prints them.
Function Scope
Inside a function, we can declare the local variables using the “local” keyword. These variables are only accessible within the function scope and do not affect the global variables with the same name.
An example is as follows:
func_name () {
local local_variable="local"
echo "In func: $local_variable"
echo "in func: $global_variable"
}
func_name
echo "Out func: $local_variable"
echo "out func: $global_variable"
In the given example, $local_variable is a local variable and only exists within the function. The global variable remains unchanged outside the function.
Function Return Values
We also define the functions that contain a return value using the “return” keyword. The returned value can be used when calling the function to perform other tasks.
local result=$(( $1 + $2 ))
return $result
}
# Call the function and capture the return value
sum=$(calculate_sum 100 33)
echo "The sum is: $sum"
This should return the sum of two integers.
Conclusion
In this post, we covered the working and usage of functions or subroutines when creating the Zsh scripts.