In this tutorial, we will dive into the principles of modularizing shell scripts with the help of functions. This technique increases the readability and maintainability of our code, leading to more efficient debugging and development.
By the end of this tutorial, you will be able to:
- Understand how to create functions in shell scripting
- Know how to call these functions within your script
- Understand how to pass arguments to functions
- Break down a larger script into smaller, manageable functions
Prerequisites:
- Basic understanding of shell scripting
- Familiarity with using a terminal/command line
In shell scripting, you create a function using the following syntax:
function_name () {
# Commands
}
The function name should be descriptive of what the function does. Inside the brackets, you write the commands that you want the function to execute.
To call a function, you simply use its name:
function_name
You can pass arguments to a function in the same way you would when running a script from the command line. Inside the function, you can access these arguments using $1
, $2
, and so on.
Let's start with a basic function that prints a greeting:
print_greeting () {
echo "Hello, world!"
}
# calling the function
print_greeting
When you run this script, you should see the following output:
Hello, world!
Now, let's create a function that takes an argument:
print_custom_greeting () {
echo "Hello, $1!"
}
# calling the function with an argument
print_custom_greeting "Alice"
When you run this, you should see:
Hello, Alice!
In this tutorial, we have learned how to create and call functions in shell scripting, and how to pass arguments to these functions. This will help you to write more structured and maintainable code.
Next, you might want to learn about function scope, return values, and more advanced function techniques. Check out these resources:
Now, try these exercises to test your understanding:
Here are the solutions:
# Exercise 1
greet () {
echo "Hello, $1!"
}
greet "Bob"
# Exercise 2
add () {
sum=$(($1 + $2))
echo "$1 + $2 = $sum"
}
add 3 5
Running these scripts should give you:
Hello, Bob!
3 + 5 = 8
Continue to practice creating functions for different tasks, and try to break down larger scripts into smaller functions.