YouTip LogoYouTip

Linux Shell Array

# Shell Arrays Arrays can hold multiple values. Bash Shell only supports one-dimensional arrays (multi-dimensional arrays are not supported), and there is no need to define the array size during initialization (similar to PHP). Similar to most programming languages, the subscripts of array elements start from 0. Shell arrays are represented by parentheses, and elements are separated by a "space" symbol. The syntax format is as follows: array_name=(value1 value2 ... valuen) ### Example Create a simple array **my_array**: ## Example #!/bin/bash # author:Tutorial # url:example.com my_array=(A B "C" D) We can also use numeric subscripts to define an array: ## Example array_name=value0 array_name=value1 array_name=value2 ### Reading Arrays The general format for reading array element values is: ${array_name} The following example reads array elements via numeric index: ## Example #!/bin/bash # author:Tutorial # url:example.com my_array=(A B "C" D) echo"The first element is: ${my_array}" echo"The second element is: ${my_array}" echo"The third element is: ${my_array}" echo"The fourth element is: ${my_array}" Execute the script, the output is as follows: $ chmod +x test.sh $ ./test.sh The first element is: A The second element is: B The third element is: C The fourth element is: D ### Associative Arrays Bash supports associative arrays, which can use arbitrary strings or integers as subscripts to access array elements. Associative arrays are declared using the (#) command. The syntax format is as follows: declare -A array_name The **-A** option is used to declare an associative array. The keys of an associative array are unique. In the following example, we create an associative array **site** and create different key-value pairs: ## Example declare-A site=(="www.google.com"="example.com"["taobao
← Docker TutorialGit Remote Repo β†’