Finally, the ${arr[-1]} is used to access the last element of the arr array, the fourth string. Let"s see another example below: Use IFS Command with a colon as Delimeter 1 2 3 4 5 6 #!/bin/bash string="first:second:third:fourth" IFS=':' read -ra arr <<< "$string"...
For example, if we have an array with five elements, the index of the last element would be 4: $ my_array=(one two three four five) $ last_element=${my_array[4]} $ echo "The 5th element is: "${last_element}"" The 5th element is: five Copy In this Bash code, we initialized...
$ 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[@]}" ## print the entire array :a 13856: :b 6235: :c 1574: :d...
array_name=(value0 value1 value2 value3) array_name=( value0 value1 value2 value3 ) array_name[0]=value0 array_name[1]=value1 array_name[n]=valuen Get an element of an array ${array_name[n]} Get all elements of an array ${array_name[@]} Get length of an array ${#array...
echo “${array[-1]}”– shows the last element ofarray reverse_array “${array[@]::length-1}”– recursively calls thereverse_arrayfunction with all thearrayelements except for the last one Now, let’s executeexample.sh: $ bash example.sh Original Array: 1 2 3 4 Reversed Array: 4 ...
# void array_push_f (avar <array>, mixed <element_value>, ...) # # Uses fastest method regardless of how indices are affected. # if [[ BASH_VERSINFO -ge 4 || (BASH_VERSINFO -eq 3 && BASH_VERSINFO[1] -ge 1) ]]; then function array_push_f { eval "$1+=(\"\${@:2}...
echo "${array[@]}" } array2=$(return_array2) declare -p array2 OUTPUT 1 2 3 4 declare -- array1="This is a sample line" declare -- array2="1 2 3 4 5" See, the array1 and array2 were returned as a string value. What if we want to get one element at a time rathe...
Used to create an array of strings. ${array[0]} Used to get the first element of the array. ${array[*]} Used to get all values in the array. ${array[1]} Get the last value in the array. ${array[@]} Expand all of the array elements. shift Move argument from $2 to $1. ...
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 ${#numbers[@]}(less than or equal to the length of the array)...
To retrieve the array you need to useparameter expansion, which involves the dollar sign and curly brackets (${ }). The positions of the elements in the array are numbered starting from zero. To get the first element of this array use${plagues[0]}like so: ...