4.0 版的bash中引入的关联数组使用字符串作为下标,并且必须在使用前声明: $ declare -A array $ for subscript in a b c d e > do > array[$subscript]="$subscript $RANDOM" > done $ printf ":%s:\n" "${array["c"]}" ## print one element :c 1574: $ printf ":%s:\n" "${array[@]...
In this example, you can see that the loop tries to process one more element than the array contains, resulting in an empty output on the last iteration. To avoid this, ensure that your loop condition isindex -lt ${#numbers[@]}(less than the length of the array), notindex -le ${#...
# Usage: random_array_element "array" local arr=("$@") printf '%s\n' "${arr[RANDOM % $#]}" } 1. 2. 3. 4. 5. 用法示例: $ array=(red green blue yellow brown) $ random_array_element "${array[@]}" yellow # Multiple arguments can also be passed. $ random_array_element 1...
An crray is like a series of slots that hold values. Each slot is known as an element, and each element can be accessed via a numerical index. An array element can contain a string or a number, and you can use it just like any other variable. The indices for arrays start at 0 and...
Notice that the first element has anindexof 0. You can get any of the elements this way, for example the fourth element: echo${plagues[3]} ## flies To get all of the elements ofplaguesuse a star (*) between the square brackets: ...
You can access an array element by referring to its index number. The index of the first element is0. For instance, to access the first element of ourmyArray, we would usemyArray[0]. Here’s how you can access individual elements: ...
But what if you want to print a specific element, then, you have to specify the index number of that element inarray[@]by replacing the@with the index number. For example, if I want to print the 5th element of the array, then, I will be using the following: ...
numbers_array[i]=”${numbers_array[j]}”– updates the element at indexito the element at indexj numbers_array[j]=”$temp”– updates the element at indexjto the original element at indexithat’s stored in thetempvariable Now, let’s see the output of the Bash scriptexample.sh: ...
Beachten Sie jedoch, dass diese Methode fehlschlagen kann, wenn ein Array-Element ein ! enthält.In unserem Beispiel unten verwenden wir das Schlüsselwort basename zum Drucken der Array-Elemente. Der Code für unser Beispiel ist unten angegeben:...
$ random_array_element 1 2 3 4 5 6 7 3 循环一个数组 每次printf调用时,都会打印下一个数组元素。当 打印到达最后一个数组元素时,它 再次从第一个元素开始。 arr=(a b c d) cycle() { printf '%s ' "${arr[${i:=0}]}" ((i=i>=${#arr[@]}-1?0:++i)) ...