-
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 its name:
function name_of_function
{
# Lines of code here
}
name_of_functionTo simply call the function, put its name at the beginning of a command line. It will cause the code between the two embraces { ... } to be executed.
As a C program, functions may return a numeric value called exit status by using the keyword return. When return is encountered, the execution of the function is stopped and the immediate value after return is returned:
function return_one
{
# Lines of code executed
return 1
# Lines of code NEVER executed
}
return_one # Call the function
echo $? # Print the exit status of the last commandWhen you declare a variable, wherever in a script and even in a function, its reference is globally accessible. To specify a variable to be local only, use the keyword local:
GLOBAL_VAR="Hello"
function display_global_and_local
{
local LOCAL_VAR="World"
echo "${GLOBAL_VAR} ${LOCAL_VAR}"
}
display_global_and_local # Print "Hello World"
echo "${GLOBAL_VAR} ${LOCAL_VAR}" # Print "Hello "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 a function display_text will cause the positional parameters to be declared:
function display_text
{
echo "$1"
}
display_text "This is the first argument"$0 is not a positional parameter, it always contains the name of the script that is currently executed.
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