Bash 数组 如果你有过编程经验,你可能已经熟悉数组了。 不过,如果你不是开发者,你需要知道的主要一点是:与变量不同,数组可以在一个名称下存储多个值。 你可以通过用空格分隔并用 括起来的值来初始化数组。示例: 要访问数组中的元素,你需要通过它们的数字索引来引用。 {notice} 请记住,你需要使用大括号。 访问单个元素,这将输出: 这将返回最后一个元素: 与命令行参数一样,使用 will return all elements in the array, as follows: 在数组前加上井号 ( ) would output the total number of elements in the array, in our case it is :
如果你有过编程经验,你可能已经熟悉数组了。
不过,如果你不是开发者,你需要知道的主要一点是:与变量不同,数组可以在一个名称下存储多个值。
你可以通过用空格分隔并用 () 括起来的值来初始化数组。示例:
my_array=("value 1" "value 2" "value 3" "value 4")
要访问数组中的元素,你需要通过它们的数字索引来引用。
{notice} 请记住,你需要使用大括号。
value 2echo ${my_array[1]}
value 4echo ${my_array[-1]}
@ will return all elements in the array, as follows: value 1 value 2 value 3 value 4echo ${my_array[@]}
#) would output the total number of elements in the array, in our case it is 4:echo ${#my_array[@]}
请务必在你的环境中使用不同的值进行测试和练习。
虽然 Bash 不支持真正的数组切片,但你可以通过结合数组索引和字符串切片来实现类似的效果:
#!/bin/bash array=("A" "B" "C" "D" "E") # Print entire array echo "${array[@]}" # Output: A B C D E # Access a single element echo "${array[1]}" # Output: B # Print a range of elements (requires Bash 4.0+) echo "${array[@]:1:3}" # Output: B C D # Print from an index to the end echo "${array[@]:3}" # Output: D E
在处理数组时,始终使用 [@] 来引用所有元素,并将参数扩展用引号括起来,以保留数组元素中的空格。
在 Bash 中,你可以使用切片来提取字符串的一部分。基本语法是:
${string:start:length}
其中:
start is the starting index (0-based)length 是要提取的最大字符数让我们看几个示例:
#!/bin/bash text="ABCDE" # Extract from index 0, maximum 2 characters echo "${text:0:2}" # Output: AB # Extract from index 3 to the end echo "${text:3}" # Output: DE # Extract 3 characters starting from index 1 echo "${text:1:3}" # Output: BCD # If length exceeds remaining characters, it stops at the end echo "${text:3:3}" # Output: DE (only 2 characters available)
请注意,切片表示法中的第二个数字表示提取子字符串的最大长度,而不是结束索引。这与其他一些编程语言(如 Python)不同。在 Bash 中,如果你指定的长度超出了字符串的末尾,它将直接在字符串末尾停止,而不会报错。
例如:
text="Hello, World!" # Extract 5 characters starting from index 7 echo "${text:7:5}" # Output: World # Attempt to extract 10 characters starting from index 7 # (even though only 6 characters remain) echo "${text:7:10}" # Output: World!
在第二个示例中,尽管我们要求提取 10 个字符,Bash 只从索引 7 到字符串末尾返回了 6 个可用字符。这种行为在你不确定所处理字符串的确切长度时特别有用。
免责声明:
本文件由基于人工智能的机器翻译服务翻译而成。尽管我们力求翻译准确,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言版本的文件为准。对于关键信息,建议使用专业的人工翻译。对于因使用本翻译而产生的任何误解或误读,我们概不负责。