Search code examples
arraysbashtabular

Creating an array of variables in Bash


I think the reason I can't Google this answer, is because I don't know the terms to use. So apologies if this post frustrates.

What I want to create is an array of multi-part variables; so that a set of keywords can correspond with a corresponding MQTT topic. The background (unrelated to the question) - I intend natural spoken language to be converted into automation triggers; once I have my table, a function can compare the spoken sentence against the array/table I am trying to create, and if the keywords match, the corresponding MQTT message is sent. I would like to use this table/array approach, so that the overall solution is easily updated.

In some imaginary language, the code to build such a table might look like this:

declare -a commandarray
{"keywords":"'lounge tv on'","mqtt":"lounge/tv{on}"} >> $commandarray
{"keywords":"'lounge tv off'","mqtt":"lounge/tv{off}"} >> $commandarray
{"keywords":"'bedroom tv on'","mqtt":"bedroom/tv{on}"} >> $commandarray
{"keywords":"'bedroom tv off'","mqtt":"bedroom/tv{off}"} >> $commandarray

I guess the result would be a table with column headers of "keywords" and "mqtt", that might display like this. I don't care how it displays, this is just to help explain myself.

keywords            mqtt
--------            --------
lounge tv on        lounge/tv{on}       
lounge tv off       lounge/tv{off}       
bedroom tv on       bedroom/tv{on}       
bedroom tv off      bedroom/tv{off} 

Any help would be very much appreciated!


Solution

  • What you're asking for is a bash 4 feature called an associative array.

    declare -A commands=(
      ["lounge tv on"]="lounge/tv{on}"
      ["lounge tv off"]="lounge/tv{off}"
      ["bedroom tv on"]="bedroom/tv{on}"
      ["bedroom tv off"]="bedroom/tv{off}"
    )
    

    A lookup is something like the following:

    input="lounge tv on"
    echo "Running command: ${commands[$input]}"
    

    ...and an assignment is akin to:

    commands["new command"]="new/command{parameter}"
    

    Associative arrays are covered in detail in BashFAQ #6, and in the bash-hackers' wiki page on arrays.