JIYIK CN >

Current Location:Home > Learning > OPERATING SYSTEM >

Passing an array to a function in Bash

Author:JIYIK Last Updated:2025/03/23 Views:

This article is all about using functions in Bash scripts and passing arrays to them. Before getting into the actual topic, we will give a brief introduction to Bash scripting.

A Bash script file contains a series of Bash commands. These commands are a combination of commands that we often type on the command line (such as ls or cp) and commands that we can type on the command line.

Any command that can be entered and executed on the command line will perform the same actions if included in a script file and run.


Functions in Bash Scripts

In shell scripts, reusable code blocks are grouped using Bash functions. Most programming languages ​​support this feature, which is also known as procedures, methods, or subroutines, among other names.

One way to store reusable code snippets under a name is called a Bash function. There are two advantages to using functions when writing Bash scripts:

  1. Reading a function directly into the shell's memory saves it for later use. Today's computers have plenty of memory, so using a function is faster than writing the same code over and over again.
  2. Functions allow you to break long shell scripts into reusable, modular chunks of code. These chunks are easier to create and keep up with.

Declaring a function in Bash

There are two ways to declare functions in Bash:

  1. One way to declare a function is to use just the function name, like this:
    <function_name> () {
         <set of commands>
    }
    
  2. Another way is to use functionthe keyword like this:
    function <function_name> {
         < set of commands>
    }
    

For both types of declarations, we can also use a single-line declaration like this:

function <function_name> { <set of commands>; }

When using functions, you must keep in mind the following facts:

  1. Whether you are using a Bash script or directly using the terminal, commands written on a line must end with a semicolon (;).
  2. When adding a function reserved word, the parentheses are optional.
  3. The body of a function consists of the commands that appear between curly braces or <pre>. Any number of declarations, variables, loops, or conditional statements are allowed in the body.
  4. Try to give descriptive function names. Descriptive names are useful when other developers are reviewing your code, but they are not needed when testing functions and commands.

Calling functions in Bash

To call a function, we use its name. Make sure you declare the function before calling it.

Let's look at the following code:

#!/bin/Bash
func1 () {
        echo Hello from function
        echo Good Bye!
}
func1

This code will give the following output:

Output of functions in Bash


Function arguments in Bash

If you want to pass arguments to a function, the arguments should be added after the function call and separated by spaces. The following table lists several options for using Bash function arguments.

parameter Purpose
$0 When a function is defined in the terminal, it stores its name. When specified in a Bash script, $0 outputs the name and location of the script.
$1, $2, etc. This corresponds to the argument position after the function name.
$# This tells the count of the total number of parameters passed.
$@ and $* This will hold the array or list type of the passed argument.
"$@" It breaks up the passed list into individual arguments, for example, "$1", "$2", etc.

Passing an array to a function in Bash

Consider the following example, where we pass an array list to a function and the function breaks it into separate variables and prints them on the screen.

#!/bin/Bash
function printArray() {
   a=("$@")
   for b in "${a[@]}";
      do
          echo "$b"
      done
}
array=("first" "second" "third")
printArray "${array[@]}

请注意, when we call the function, we pass the arguments as a list enclosed in parentheses. This will make them an array and the function will save them in $@.

We then loop over and print the array.

Output:

Output of array transfer function

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Creating a Progress Bar in Bash

Publish Date:2025/03/23 Views:94 Category:OPERATING SYSTEM

A progress bar is a visual indicator that shows the progress of a task, such as a long-running script or command. It can be used to provide feedback to the user about the status of a task and can also help estimate the time remaining before

Redirecting Stderr and Stdout to a file in Bash

Publish Date:2025/03/23 Views:187 Category:OPERATING SYSTEM

In this article, we will discuss standard output and standard error in Linux. We will see how to redirect standard output and standard error in Bash. Let us start by understanding the terms standard output and standard error in Linux. Stand

Deleting Duplicate Lines in Bash

Publish Date:2025/03/23 Views:123 Category:OPERATING SYSTEM

Duplicate entries can cause a variety of problems in Bash scripts, such as incorrect or inconsistent results, and they can also make the script difficult to maintain. Removing duplicate entries from a script is often necessary to avoid thes

Count unique lines in a file in Linux

Publish Date:2025/03/23 Views:190 Category:OPERATING SYSTEM

Counting unique lines in a file is a common task in Linux, and there are a number of different tools and methods that can be used to perform this operation. In general, the appropriate method depends on the specific requirements and constra

Counting files in a directory in Bash

Publish Date:2025/03/23 Views:178 Category:OPERATING SYSTEM

Counting how many files are in a directory is a common task in Bash, and there are a number of different tools and methods that can be used to perform this operation. In general, the appropriate method depends on the specific requirements a

Execute commands in a variable in a Bash script

Publish Date:2025/03/23 Views:111 Category:OPERATING SYSTEM

This article is about storing Bash commands in a variable and then executing it directly from that variable. First, we will discuss the various ways to execute commands contained in a variable, followed by several script examples. Let’s g

Bash variable multiplication

Publish Date:2025/03/23 Views:150 Category:OPERATING SYSTEM

This article explains how to multiply two variables in Bash. Multiplying variables in Bash Multiplying two variables is a simple operation in Bash. We can use the arithmetic operator * to multiply two numbers in Bash. In Bash, multiplicatio

Bash md5sum command

Publish Date:2025/03/23 Views:116 Category:OPERATING SYSTEM

This article explains how to use the md5sum command in Bash. Bash md5sum command md5sum command prints the 32 character and 128 bit checksum of a given file. This command converts the file into a hash using the MD5 algorithm; the syntax of

Sorting Arrays in Bash

Publish Date:2025/03/23 Views:73 Category:OPERATING SYSTEM

Sorting an array is a very common task in any programming language. In Bash scripting, we can also accomplish this task in two different ways. The first one uses any sorting algorithm and the second one uses a built-in keyword in Bash scrip

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial