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

How to decompress x.tar.xz format files under Linux

Publish Date:2025/04/08 Views:186 Category:OPERATING SYSTEM

A lot of software found today is in the tar.xz format, which is a lossless data compression file format that uses the LZMA compression algorithm. Like gzip and bzip2, it supports multiple file compression, but the convention is not to compr

Summary of vim common commands

Publish Date:2025/04/08 Views:115 Category:OPERATING SYSTEM

In Linux, the best editor should be vim. However, the complex commands behind vim's powerful functions also make us daunted. Of course, these commands do not need to be memorized by rote. As long as you practice using vim more, you can reme

Detailed explanation of command return value $? in Linux

Publish Date:2025/04/08 Views:58 Category:OPERATING SYSTEM

? is a special variable. This variable represents the return value of the previous command. That is to say, when we run certain commands, these commands will return a code after running. Generally, if the command is successfully run, the re

Common judgment formulas for Linux script shell

Publish Date:2025/04/08 Views:159 Category:OPERATING SYSTEM

In shell script programming, predicates are often used. There are two ways to use predicates, one is to use test, and the other is to use []. Let's take a look at how to use these two methods through two simple examples. Example 1 # test –

How to use the Linux file remote copy command scp

Publish Date:2025/04/08 Views:151 Category:OPERATING SYSTEM

Scp copies files between two hosts over the network, and the data is encrypted during transmission. Its underlying layer uses ssh for data transmission. And it has the same authentication mechanism and the same security level as ssh. When u

Scan to Read All Tech Tutorials

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

Recommended

Tags

Scan the Code
Easier Access Tutorial