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

  1. Open your terminal or shell.
  2. 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
  1. Type the following code into the file:
#!/bin/bash

# Defining a function
function greet() {
  echo "Hello, $1"
}

# Calling a function
greet "book"
  1. Save the file and exit the editor.
  2. Make the file executable by running the following command in the terminal:chmod +x functions.sh
chmod +x functions.sh
  1. 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.

Bash-Tips-script-function

Leave a Reply

Scroll to Top