texonec238
texonec238

Reputation: 25

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

Upvotes: 0

Views: 99

Answers (2)

Ed Morton
Ed Morton

Reputation: 204456

Don't use a bunch of separate variables with numeric suffixes 1 to 3, use an array with numeric indices 1 to 3, e.g.:

$ input='001101001101101110111011'
$ readarray -t var <<<"${input//????????/$'\n'&}"

$ echo "${var[1]}"
00110100
$ echo "${var[2]}"
11011011
$ echo "${var[3]}"
10111011

You could use:

"${input//?$(printf '?%.0s' {1..7})/$'\n'&}"

instead of hard-coding 8 ?s but. while the printf '<string>%.0s' {1..<N>} idiom can be useful for generating N+1 repeating strings in other contexts, it's unnecessarily complicated for this case.

As pointed out by @pjh in a comment, bash pattern replacement using & depends on the patsub_replacement shopt option which was introduced with Bash 5.2, released in September 2022. If you don't have that available you can always use some versions of sed:

readarray -t var < <(sed 's/.\{8\}/\n&/g' <<<"$input")

or any awk:

readarray -t var < <(awk '{gsub(/.{8}/,"\n&")}1' <<<"$input")

Either of the above scripts will also populate an empty var[0], just don't use it and use indices starting at 1 as indicated in your question.

Upvotes: 1

mandy8055
mandy8055

Reputation: 6735

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

Upvotes: 2

Related Questions