-1

I am trying to use the variable $i from a for statement as part of another variable name within an if statement.

I have the following function as part of a script:

online () {

        for i in $processors; do


                if ping -c1 $i &> /dev/null; then
                        ${i}status="Online"     
                else
                        ${i}status="Offline"
                fi

        done
}

The output of the if statement is treated as a command and not as a declared variable. I want to use the dynamic variable several times in another function later in the script.

Is there any way to do this or do I need to work out another solution?

markp-fuso
  • 28,790
  • 4
  • 16
  • 36
  • 1
    See [BashFAQ #6](https://mywiki.wooledge.org/BashFAQ/006). That said, I'd suggest using an associative array instead: `declare -A status` and then later `status[$i]=Online` to set a value you can look up with `"${status[$i]}"` later. – Charles Duffy Aug 03 '23 at 14:28
  • BTW, `for i in $processors` is itself bad form -- implies that you have your "processors" stored in a string variable instead of an array. Look up shell arrays; once you're using one it would be `for i in "${processors[@]}"`, which is less sensitive to IFS values, globbing behaviors, and other surprises. – Charles Duffy Aug 03 '23 at 14:30

0 Answers0