0

When executing the following Bash function, the command substitution does work, but variable assignment fails and the shell interprets the NEW_ADDRESS$n= as a command instead, throwing off "Command not found" errors.

The aim of the code is to have X number of NEW_ADDRESS$n variables assigned with the output of the "printf $line | base58 -c" command, which takes a file containing multiple lines of hex bytes. How do I make this work?

generate_addresses() {
    hex_input=$1
    n=1
    while read -r line; do
        NEW_ADDRESS$n=$( printf $line | base58 -c )
        n=$((n+1))
    done < $hex_input
    }

generate_addresses $1
zyk
  • 111
  • 1
  • 3
  • Try to remove the spaces between $( and print. Bash is very strict with its syntax – George Sp Dec 10 '18 at 22:43
  • @GeorgeSp Spaces after `$(` are not a problem. – Socowi Dec 10 '18 at 22:49
  • 1
    Indirect assignment *is* the problem here, but we already have Q&A entries showing how to do it correctly. `foo$bar=$baz` simply isn't valid syntax in bash (and nothing in the docs ever said it was). – Charles Duffy Dec 10 '18 at 22:51
  • [BashFAQ #6](https://mywiki.wooledge.org/BashFAQ/006#Assigning_indirect.2Freference_variables) is also pertinent. That said, in this specific case, the OP should probably just use a *single* array variable, rather than a bunch of separate variables storing strings in the first place. `new_addresses[$n]=$(base58 -c <<<"$line")` is pretty easy. – Charles Duffy Dec 10 '18 at 22:52
  • Also consider using `printf %s "$line"` instead of `printf $line`. You can abbreviate `n=$((n+1))` with `((n++))`. – Socowi Dec 10 '18 at 22:53
  • (btw, `printf $line` is buggy on several counts -- because `$line` is unquoted it gets string-split and glob-expanded, then the first word it was split into is used as the format string, and other words are treated as arguments use to fill in placeholders in that string). – Charles Duffy Dec 10 '18 at 22:53
  • @Socowi, ...`<<<"$line"` is more efficient -- sure, it creates a temporary file, but on modern systems with tmpfs or equivalents that's cheaper than setting up a FIFO and forking a subshell to be the left-hand side of it. – Charles Duffy Dec 10 '18 at 22:54
  • Similarly, the argument in `generate_addresses $1` should be quoted as `"$1"` so prevent that argument from being munged in the same manner. – Charles Duffy Dec 10 '18 at 22:55
  • As suggested, `NEW_ADDRESS[$n]=$( printf $line | base58 -c)` works. However just an FYI, `printf` is required or the base58 program outputs incorrect values. Thank you. – zyk Dec 10 '18 at 23:16

0 Answers0