-
Notifications
You must be signed in to change notification settings - Fork 56
Bash syntax: Functions
Functions enable you to structure your code, to increase readability and to avoid repetition of lines of code.
Declare a function by using the keyword function
followed by a name. In this example, we will create a function for displaying text in the middle of a line in a terminal, we call it display_center
:
function display_center
{
# Lines of code here
}
Calling the function display_center
will cause the code between the two embraces { ... }
to be executed. As a C program, functions may return a numeric value by using the keyword ret
. When ret
is encountered, the execution of the function is stopped and the immediate value after ret
is returned:
function return_zero
{
# Lines of code are executed
ret 0
# Lines of code NEVER executed
}
In Bash programming, the arguments of a function are not explicitly declared. As you read it in the chapter "Bash syntax: Variables", the arguments of a script or a function are called positional parameters. They are listed and named like this: $1
, $2
, $3
...
Passing a list of arguments to our function display_center
will cause the positional parameters to be automaticaly declared:
function display_center
{
echo "$1"
}
Introduction:
- What is Bash
- What is a bash script
- What is 42FileChecker
- Contributing to 42FileChecker
Bash syntax:
Bash tools:
- Builtin commands
- Awk
- Cat
- Grep
- Sed
Bash sample codes:
- Script auto-update (git tool)
- Create an interactive menu
- Animated spinner with a time out
- Static var test
- Check the basic rules of a makefile
- Forbidden functions test
- Memory leak test script
- Create a speed test