Tutorial by Examples

List Assignment If you are familiar with Perl, C, or Java, you might think that Bash would use commas to separate array elements, however this is not the case; instead, Bash uses spaces: # Array in Perl my @array = (1, 2, 3, 4); # Array in Bash array=(1 2 3 4) Create an array with new ...
Print element at index 0 echo "${array[0]}" 4.3 Print last element using substring expansion syntax echo "${arr[@]: -1 }" 4.3 Print last element using subscript syntax echo "${array[-1]}" Print all elements, each quoted separately echo "${array[@...
${#array[@]} gives the length of the array ${array[@]}: array=('first element' 'second element' 'third element') echo "${#array[@]}" # gives out a length of 3 This works also with Strings in single elements: echo "${#array[0]}" # gives out the lenght of the string at ele...
Change Index Initialize or update a particular element in the array array[10]="elevenths element" # because it's starting with 0 3.1 Append Modify array, adding elements to the end if no subscript is specified. array+=('fourth element' 'fifth element') Replace the entire ar...
Array iteration comes in two flavors, foreach and the classic for-loop: a=(1 2 3 4) # foreach loop for y in "${a[@]}"; do # act on $y echo "$y" done # classic for-loop for ((idx=0; idx < ${#a[@]}; ++idx)); do # act on ${a[$idx]} echo "${a[$idx]}&...
To destroy, delete, or unset an array: unset array To destroy, delete, or unset a single array element: unset array[10]
4.0 Declare an associative array declare -A aa Declaring an associative array before initialization or use is mandatory. Initialize elements You can initialize elements one at a time as follows: aa[hello]=world aa[ab]=cd aa["key with space"]="hello world" You can al...
Get the list of inialized indexes in an array $ arr[2]='second' $ arr[10]='tenth' $ arr[25]='twenty five' $ echo ${!arr[@]} 2 10 25
Our example array: arr=(a b c d e f) Using a for..in loop: for i in "${arr[@]}"; do echo "$i" done 2.04 Using C-style for loop: for ((i=0;i<${#arr[@]};i++)); do echo "${arr[$i]}" done Using while loop: i=0 while [ $i -lt ${#arr[@]} ]; do...
stringVar="Apple Orange Banana Mango" arrayVar=(${stringVar// / }) Each space in the string denotes a new item in the resulting array. echo ${arrayVar[0]} # will print Apple echo ${arrayVar[3]} # will print Mango Similarly, other characters can be used for the delimiter. stringVa...
This function will insert an element into an array at a given index: insert(){ h=' ################## insert ######################## # Usage: # insert arr_name index element # # Parameters: # arr_name : Name of the array variable # index : Index to insert at #...
Reading in a single step: IFS=$'\n' read -r -a arr < file Reading in a loop: arr=() while IFS= read -r line; do arr+=("$line") done 4.0 Using mapfile or readarray (which are synonymous): mapfile -t arr < file readarray -t arr < file

Page 1 of 1