Returning an array in Bash
Since Bash does not handle arrays, returning an array can be a bit difficult. However, it is possible to overcome this limitation by returning an array from a function using a global variable or a command substitution workaround.
This article introduces command substitution, a way to return arrays in bash without global variables.
Command Substitution
To understand how this works, we first need to understand what command substitution is and how it works in Bash.
A Bash feature called command substitution allows the output of a command to be used in place of the command itself. This is done
by enclosing the command in a pair of backticks (``)
or , as shown below:$()
echo "The current date is: `date`"
Output:
The current date is: Fri Nov 29 16:14:23 PST 2022
In the example above the date command is executed and its output is replaced with the command itself. This allows us to embed the output of a command directly into a string, which is useful in many situations.
Returning an Array Using Command Substitution in Bash
Now, let's see how to use command substitution to return an array from a function in Bash.
First, let's create a function called get_array that returns an array of numbers from 1 to 10 and use command substitution. Then, call the function and store the output in the variable result, which we will print.
function get_array() {
local my_array=(1 2 3 4 5 6 7 8 9 10)
echo "${my_array[@]}"
}
result=$(get_array)
echo "The result is: $result"
Output:
The result is: 1 2 3 4 5 6 7 8 9 10
In the function above, we create an array called my_array containing the numbers from 1 to 10. We then print the array using echo and enclose it in quotes to ensure that the array elements remain as a single string. After that, we call the get_array function and store its output in the result variable. We then print the contents of the result variable, which should be an array of numbers from 1 to 10.
Returning Arrays Using IFS in Bash
Now let us see how to get the elements of an array. Since the array elements are returned as a single string, we need to use the IFS (Internal Field Separator) variable to split the string into individual elements.
The IFS variable controls how bash splits a string into words or tokens. By default, IFS is set to space, tab, and newline, which means that bash will split a string into words at any of these characters.
To split the string returned by the get_array function into individual elements, we need to set IFS to the space character:
IFS=' '
result=$(get_array)
result_array=($result)
for i in "${!result_array[@]}"; do
echo "Element $i: ${result_array[$i]}"
done
Output:
Element 0: 1
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5
Element 5: 6
Element 6: 7
Element 7: 8
Element 8: 9
Element 9: 10
In the code above, we set IFS to a space character, which allows us to split the string returned by the get_array function into individual elements. We then store the results in the result_array variable and use a for loop to print the elements of the array.
Now let's see how this method returns an array of strings instead of an array of numbers.
First, let's modify the get_array function to return an array of strings:
function get_array() {
local my_array=("one" "two" "three" "four" "five" "six" "seven" "eight" "nine" "ten")
# Return the array using the command substitution
echo "${my_array[@]}"
}
In the function above, we create an array called my_array that contains the strings 1 to 10. We then print the array using echo and enclose it in quotes to ensure that the array elements remain as a single string.
Now let's see how to use the get_array function to return an array of strings:
IFS=' '
result=$(get_array)
result_array=($result)
for i in "${!result_array[@]}"; do
echo "Element $i: ${result_array[$i]}"
done
Output:
Element 0: one
Element 1: two
Element 2: three
Element 3: four
Element 4: five
Element 5: six
Element 6: seven
Element 7: eight
Element 8: nine
Element 9: ten
In the above code, we called the get_array function and stored its output in the result variable. Then we split the string into individual elements and stored them in the result_array variable.
Finally, we use a for loop to print the elements of the array.
In summary, returning an array in bash can be tricky because bash doesn't support arrays. However, you can use a technique called command substitution to get it working.
This involves enclosing the array in quotes and printing it using echo, then splitting the resulting string into individual elements using the IFS variable.
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.
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 –
Shell script programming practice - specify a directory to delete files
Publish Date:2025/04/08 Views:98 Category:OPERATING SYSTEM
-
Usually, in Linux system we need to frequently delete some temporary files or junk files. If we delete them one by one manually, it will be quite troublesome. I have also been learning shell script programming recently, so I tried to write
Use of Linux command at - set time to execute command only once
Publish Date:2025/04/08 Views:158 Category:OPERATING SYSTEM
-
This article mainly involves a knowledge point, which is the atd service. Similar to this service is the crond service. The functions of these two services can be similar to the two functional functions of javascript. Those who have learned
Use of Linux command crontab - loop execution of set commands
Publish Date:2025/04/08 Views:170 Category:OPERATING SYSTEM
-
Compared with at , which executes a command only once, crontab, which we are going to talk about in this article, executes the set commands in a loop. Similarly, the use of crontab requires the support of the crond service. The service is s
Linux practice - regularly delete files under the directory
Publish Date:2025/04/08 Views:198 Category:OPERATING SYSTEM
-
Since we want to delete the files under the directory regularly, we need to use the Linux crontab command. And the content format of each work routine is also introduced in the format of each crontab work. Similarly, we need to use shell sc
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