Bash Script Function
- Read
- Discuss
A function in a bash script is a reusable block of code that can be executed by calling its name. Functions help to organize and structure your code and can be used to perform a specific task.
Lets create function
- Open your terminal or shell.
- Create a new file using a text editor of your choice. For example, you can use the nano editor to create a file called “functions.sh”:
nano functions.sh
- Type the following code into the file:
#!/bin/bash
# Defining a function
function greet() {
echo "Hello, $1"
}
# Calling a function
greet "book"
- Save the file and exit the editor.
- Make the file executable by running the following command in the terminal:chmod +x functions.sh
chmod +x functions.sh
- Finally, run the script by typing:
./functions.sh
You should see the message “Hello, book” printed in the terminal.
And that’s it! This is a simple example of how to use functions in a Bash script. Functions are blocks of code that can be executed multiple times from different parts of the script. In Bash, you define a function using the function keyword, followed by the function name and the commands in braces.
