Search code examples
bashsplitdynamic-variables

Break variable to dynamic variables


The script accepts input as binary of various character length.

For example input can be 00011010 or 001101001101101110111011 (up to 9 sets of 8bits) I have managed to split them per 8 bit.

input_space=$(echo "$input" | sed 's/.\{8\}/& /g')

How can every 8bit set can be stored as a separate dynamic variable?

i.e. var1=00110100 var2=11011011 var3=10111011


Solution

  • You can store the 8-bit sets in an array and then access them dynamically.

    #!/bin/bash
    
    input="001101001101101110111011"
    
    input_space=($(echo "$input" | sed 's/.\{8\}/& /g'))
    
    for i in "${!input_space[@]}"; do
        var_name="var$(($i+1))"
        declare "$var_name=${input_space[$i]}"
        echo "$var_name=${!var_name}"
    done
    

    The above script:

    1. Splits the input into 8-bit sets,
    2. Stores them in the input_space array, and then
    3. Iterates over the array to create dynamic variables (var1, var2, var3, etc.) using the declare command. The ${!var_name} notation is used to indirectly reference the value of the dynamic variable. Reference