bash shell数组详解

本文详细介绍了如何在Bash中创建和操作字符串索引数组,包括打印数组、获取数组长度以及访问最后一个元素的方法。通过示例展示了如何使用零索引访问数组元素,并解释了为什么需要使用花括号。此外,还提到了从Bash 4.2开始支持的负索引特性,使得从数组末尾访问元素变得更加便捷。
摘要由CSDN通过智能技术生成

原始文章:https://codefather.tech/blog/bash-array/
Bash Indexed Array of Strings
We will start by creating an indexed array of strings where the strings are directory names in a Linux system:

dirs=(“/etc” “/var” “/opt” “/tmp”)
First of all let’s see what gets printed when we echo the value of the array variable dirs:

$ echo $dirs
/etc
When you print a Bash array variable the result is the first element of the array.

Another way to print the first element of the array is by accessing the array based on its index.

Bash indexed arrays are zero based, this means that to access the first element we have to use the index zero.

$ echo ${dirs[0]}
/etc
Wonder why we are using curly brackets?

We can understand why by removing them to see what the ouput is:

$ echo $dirs[0]
/etc[0]
Bash prints the first element of the array followed by [0] because it only recognises $dirs as a variable. To include [0] as part of the variable name we have to use curly brackets.

In the same way, to print the second element of the array we will access the index 1 of the array:

$ echo ${dirs[1]}
/var
What if we want to access the last element of the array?

Before doing that we have to find out how to get the length of a Bash array…

How Do You Determine the Length of a Bash Array?
To find the length of an array in Bash we have to use the syntax ${#array_name[@]}.

Let’s apply it to our example:
$ echo ${#dirs[@]}
4
The syntax might seem hard to remember when you see it for the first time…

…but don’t worry, just practice it a few times and you will remember it.

Access the Last Element of a Bash Array
Now that we know how to get the number of elements in a Bash array, we can use this information to retrieve the value of the last element.

First we have to calculate the index of the last element that is equal to the number of elements in the array minus one (remember that Bash arrays are zero-based as usually happens in most programming languages).

${#dirs[@]}-1
This value will be the index to pass when we want to print the last element of the array:
$ echo KaTeX parse error: Expected '}', got 'EOF' at end of input: {dirs[{#dirs[@]}-1]}
/tmp
Definitely not one of the easiest ways to retrieve the last element of an array, if you are familiar with other programming languages 😀

Since Bash 4.2 arrays also accept negative indexes that allow to access elements starting from the end of the array.

To verify your version of Bash use the following command:

$ bash --version

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值