Top
JohnKlann / bash  / Basic Array Syntax, Iteration, Manipulation

Basic Array Syntax, Iteration, Manipulation

So I recently took on a project where one of the requirements is that it has to be completed in Linux Bash and have as little outside dependencies as possible. So As Bash does not support multi-dimensional arrays, i’ll just cover array basics for now lol.

  1. Array Declaration:
    ARR=()
    
  2. Adding to Array
    1. values
      ARR+=('value')
      
    2. variables
      ARR+=("$VAR")
      
  3. Getting Array Length
    ARRLEN=${#ARR[@]}
    
  4. Iterating/Looping through Array (be mindful of your spacing)
    for (( i=0; i<${ARRLEN}; i++ )); do
    	echo "${ARR[$i]}"
    done
    
  5. Putting it all together:
    #!/bin/bash
    
    ARR=()
    
    VAR="World"
    
    echo "adding value to array"
    
    ARR+=('hello')
    
    ARRLEN=${#ARR[@]}
    
    echo "Array length is now: $ARRLEN"
    
    echo "adding variable to array"
    
    ARR+=("$VAR")
    
    ARRLEN=${#ARR[@]}
    
    echo "Array length is now: $ARRLEN"
    
    echo "loop through array"
    
    for (( i=0; i<${ARRLEN}; i++ )); do
            echo "Array Key/Index: $i holds Value: ${ARR[$i]}"
    done
    
  6. Returns:

linux_bash_basic_array_operations