Bash 基础知识系列 #5：在 Bash 中使用数组
脚本 Bash
![](/data/attachment/album/202307/20/150302ttfmzchutthfcncm.jpg)



> 
> 本章将介绍如何在 Bash Shell 脚本中使用数组。学习添加元素、删除元素和获取数组长度。
> 
> 
> 


在本系列的前面部分中，你了解了变量。变量中可以有单个值。


数组内部可以有多个值。当你必须一次处理多个变量时，这会使事情变得更容易。你不必将各个值存储在新变量中。


因此，不要像这样声明五个变量：



```
distro1=Ubuntu
distro2=Fedora
distro3=SUSE
distro4=Arch Linux
distro5=Nix

```

你可以在单个数组中初始化它们所有：



```
distros=(Ubuntu Fedora SUSE "Arch Linux" Nix)

```

与其他一些编程语言不同，你不使用逗号作为数组元素分隔符。


那挺好的。让我们看看如何访问数组元素。


### 在 Bash 中访问数组元素


使用索引（数组中的位置）访问数组元素。要访问索引 N 处的数组元素，请使用：



```
${array_name[N]}

```


> 
> ? 与大多数其他编程语言一样，Bash Shell 中的数组从索引 0 开始。这意味着第一个元素的索引为 0，第二个元素的索引为 1，第 n 个元素的索引为 `n-1`。
> 
> 
> 


因此，如果你想打印 SUSE，你将使用：



```
echo ${distros[2]}

```

![Example of accessing array elements in bash shell](/data/attachment/album/202307/20/150331v71tmaqm1jzd77dw.png)



> 
> ? `${` 之后或 `}` 之前不能有任何空格。你不能像 `${ array[n] }` 那样使用它。
> 
> 
> 


### 一次访问所有数组元素


假设你要打印数组的所有元素。


你可以一一使用 `echo ${array[n]}` 但这确实没有必要。有一个更好更简单的方法：



```
${array[*]}

```

这将为你提供所有数组元素。


![Accessing all array elements at once in bash shell](/data/attachment/album/202307/20/150331gwjdj0sg0bgjkol6.png)


### 在 Bash 中获取数组长度


如何知道数组中有多少个元素？ 有一个专门的方法 [在 Bash 中获取数组长度](https://linuxhandbook.com:443/array-length-bash/)：



```
${#array_name[@]}

```

就这么简单，对吧？


![Get array length in bash](/data/attachment/album/202307/20/150332q41cz17smbwb84wx.png)


### 在 Bash 中添加数组元素


如果必须向数组添加其他元素，请使用 `+=` 运算符 [将元素追加到 Bash 中的现有数组](https://linuxhandbook.com:443/bash-append-array/)：



```
array_name+=("new_value")

```

这是一个例子：


![Append new element to array](/data/attachment/album/202307/20/150332rmyaqvwwuajzusq8.png)



> 
> ? 追加元素时使用 `()` 很重要。
> 
> 
> 


你还可以使用索引将元素设置在任何位置。



```
array_name[N]=new_value

```

**但请记住使用正确的索引编号。** 如果在现有索引上使用它，新值将替换该元素。


如果你使用“越界”索引，它仍会添加到最后一个元素之后。例如，如果数组长度为 6，并且你尝试在索引 9 处设置新值，则该值仍将作为最后一个元素添加到第 7 个位置（索引 6）。


![](/data/attachment/album/202307/20/150332e611mwv3awqmipwp.png)


### 删除数组元素


你可以使用 Shell 内置的 `unset` 通过提供索引号来删除数组元素：



```
unset array_name[N]

```

这是一个示例，我删除了数组的第四个元素。


![Delete array element in bash](/data/attachment/album/202307/20/150333efv3q6qga3urrviq.png)


你还可以通过 unset 来删除整个数组：



```
unset array_name

```


> 
> ? Bash 中没有严格的数据类型规则。你可以创建一个同时包含整数和字符串的数组。
> 
> 
> 


### ?️ 练习时间


让我们练习一下你所学到的有关 Bash 数组的知识。


**练习 1**：创建一个 Bash 脚本，其中包含五个最佳 Linux 发行版的数组。全部打印出来。


现在，用 “Hannah Montanna Linux” 替换中间的选择。


**练习 2**：创建一个 Bash 脚本，该脚本接受用户提供的三个数字，然后以相反的顺序打印它们。


预期输出：



```
Enter three numbers and press enter
12 23 44
Numbers in reverse order are: 44 23 12

```

我希望你喜欢通过本系列学习 Bash Shell 脚本。在下一章中，你将学习如何使用 `if-else`。敬请关注。


*（题图：MJ/09477e2f-2bf9-4fdf-bc1e-c894a068adf2）*




---


via: <https://itsfoss.com/bash-arrays/>


作者：[Abhishek Prakash](https://itsfoss.com/author/abhishek/) 选题：[lkxed](https://github.com/lkxed/) 译者：[geekpi](https://github.com/geekpi) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
# Chapter #5: Using Arrays in Bash

Time to use arrays in bash shell scripts in this chapter. Learn to add elements, delete them and get array length.

In the earlier part of the series, you learned about variables. The variables can have a single value in it.

Arrays can have several values inside it. This makes things easier when you have to deal with several variables at a time. You don't have to store individual values in a new variable.

So, instead of declaring five variables like this:

```
distro1=Ubuntu
distro2=Fedora
distro3=SUSE
distro4=Arch Linux
distro5=Nix
```


You can initialize all of them in a single array:

`distros=(Ubuntu Fedora SUSE "Arch Linux" Nix)`


Unlike some other programming languages, you don't use commas as array element separators.

That's good. Let's see how to access the array elements.

## Accessing array elements in bash

The array elements are accessed using the index (position in the array). To access array element at index N, use:

`${array_name[N]}`


`nth`

element has index `n-1`

.So, if you want to print the SUSE, you'll use:

`echo ${distros[2]}`


![Example of accessing array elements in bash shell](https://itsfoss.com/content/images/2023/07/accessing-array-elements-bash.png)

`${`

or before `}`

. You CANNOT use it like ${ array[n] }.## Access all array elements at once

Let's say you want to print all the elements of an array.

You may use echo ${array[n]} one by one but that's really not necessary. There is a better and easier way:

`${array[*]}`


That will give you all the array elements.

![Accessing all array elements at once in bash shell](https://itsfoss.com/content/images/2023/07/accessing-all-array-elements-bash.png)

## Get array length in bash

How do you know how many elements are there in an array? There is a dedicated way to [get array length in Bash](https://linuxhandbook.com/array-length-bash/):

`${#array_name[@]}`


That's so simple, right?

![Get array length in bash](https://itsfoss.com/content/images/2023/07/get-array-length-bash.png)

## Add array elements in bash

If you have to add additional elements to an array, use the `+=`

operator to [append element to existing array in bash](https://linuxhandbook.com/bash-append-array/):

`array_name+=("new_value")`


Here's an example:

![Append new element to array](https://itsfoss.com/content/images/2023/07/append-element-to-array.png)

`()`

while appending an element.You can also use the index to set the element at any position.

`array_name[N]=new_value`


**But remember to use the correct index number.** If you use it on an existing index, the new value will replace the element.

If you use an 'out of bound' index, it will still be added after the last element. For example, if the array length is six and you try to set a new value at index 9, it will still be added as the last element at the 7th position (index 6).

![](https://itsfoss.com/content/images/2023/07/add-array-element-bash-1.png)

## Delete an array element

You can use `unset`

shell built-in to remove an array element by providing the index number:

`unset array_name[N]`


Here's an example, where I delete the 4th element of the array.

![Delete array element in bash](https://itsfoss.com/content/images/2023/07/delete-array-element-bash.png)

You can also delete the entire array with unset:

`unset array_name`


## 🏋️ Exercise time

Let's practice what you learned about bash arrays.

**Exercise 1**: Create a bash script that has an array of five best Linux distros. Print them all.

Now, replace the middle choice with Hannah Montanna Linux.

**Exercise 2**: Create a bash script that accepts three numbers from the user and then prints them in reverse order.

Expected output:

```
Enter three numbers and press enter
12 23 44
Numbers in reverse order are: 44 23 12
```


You can discuss your answers in the dedicated thread in the Community.

[Practice Exercise in Bash Basics Series #5: Using Arrays in BashIf you are following the Bash Basics series on It’s FOSS, you can submit and discuss the answers to the exercise at the end of the chapter: Fellow experienced members are encouraged to provide their feedback to new members. Do note that there could be more than one answer to a given problem.](https://itsfoss.community/t/practice-exercise-in-bash-basics-series-5-using-arrays-in-bash/10924)![](https://itsfoss.community/uploads/default/original/1X/f274f9749e3fd8b4d6fbae1cf90c5c186d2f699c.png)


![](https://itsfoss.community/uploads/default/original/1X/f274f9749e3fd8b4d6fbae1cf90c5c186d2f699c.png)

I hope you are enjoying learning bash shell scripting with this series. In the next chapter, you'll learn about [handling strings in bash](https://itsfoss.com/bash-strings/). Stay tuned.

[Bash Basics Series #6: Handling String OperationsIn this chapter of the Bash Basics series, learn to perform various common string operations like extracting, replacing and deleting substrings.](https://itsfoss.com/bash-strings/)![](https://itsfoss.com/content/images/2023/07/bash-series-6-strings.png)


![](https://itsfoss.com/content/images/2023/07/bash-series-6-strings.png)