Associative Arrays in Shell Scripts












10















I saw a trick for implementing associative arrays in a shell script. For example print array["apples"] could be scripted as echo $array$key where key=apples.



However, there was no mention of how to generate the keys to iterate over the array.
The only way I could think of was to store the keys in a variable delimited by spaces so I could use a for-loop to iterate over the array.



So, is there some other way to store the keys for later use?










share|improve this question




















  • 5





    If you're trying to use associative arrays in a shell script it could be possible that your project is too complex for a shell script :)

    – Martin von Wittich
    Jan 29 '14 at 0:09











  • @MartinvonWittich why? I have a shell script that executes a SQL script on one of 3 possible DB schemas. The required schema is included in filename with an abbreviation. I need a mapping between this abbreviation and the real schema name. What better way than an associative array, considering the actual schema names (not the abbreviation) may differ between environments, so an array variable (whose values can be set just once) is perfect

    – Slav
    Nov 19 '14 at 14:16






  • 2





    @Slav I'm not arguing against associative arrays, just against shell scripts where such complexity is needed. But that's just my personal preference; I often catch myself starting to write a shell script and then immediately rewriting it in Perl when I realize that I'm exceeding a certain complexity threshold.

    – Martin von Wittich
    Nov 19 '14 at 22:50
















10















I saw a trick for implementing associative arrays in a shell script. For example print array["apples"] could be scripted as echo $array$key where key=apples.



However, there was no mention of how to generate the keys to iterate over the array.
The only way I could think of was to store the keys in a variable delimited by spaces so I could use a for-loop to iterate over the array.



So, is there some other way to store the keys for later use?










share|improve this question




















  • 5





    If you're trying to use associative arrays in a shell script it could be possible that your project is too complex for a shell script :)

    – Martin von Wittich
    Jan 29 '14 at 0:09











  • @MartinvonWittich why? I have a shell script that executes a SQL script on one of 3 possible DB schemas. The required schema is included in filename with an abbreviation. I need a mapping between this abbreviation and the real schema name. What better way than an associative array, considering the actual schema names (not the abbreviation) may differ between environments, so an array variable (whose values can be set just once) is perfect

    – Slav
    Nov 19 '14 at 14:16






  • 2





    @Slav I'm not arguing against associative arrays, just against shell scripts where such complexity is needed. But that's just my personal preference; I often catch myself starting to write a shell script and then immediately rewriting it in Perl when I realize that I'm exceeding a certain complexity threshold.

    – Martin von Wittich
    Nov 19 '14 at 22:50














10












10








10


5






I saw a trick for implementing associative arrays in a shell script. For example print array["apples"] could be scripted as echo $array$key where key=apples.



However, there was no mention of how to generate the keys to iterate over the array.
The only way I could think of was to store the keys in a variable delimited by spaces so I could use a for-loop to iterate over the array.



So, is there some other way to store the keys for later use?










share|improve this question
















I saw a trick for implementing associative arrays in a shell script. For example print array["apples"] could be scripted as echo $array$key where key=apples.



However, there was no mention of how to generate the keys to iterate over the array.
The only way I could think of was to store the keys in a variable delimited by spaces so I could use a for-loop to iterate over the array.



So, is there some other way to store the keys for later use?







shell-script associative-array






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 2 '16 at 13:05









dkb

1296




1296










asked Jan 28 '14 at 22:35









EggHeadEggHead

175128




175128








  • 5





    If you're trying to use associative arrays in a shell script it could be possible that your project is too complex for a shell script :)

    – Martin von Wittich
    Jan 29 '14 at 0:09











  • @MartinvonWittich why? I have a shell script that executes a SQL script on one of 3 possible DB schemas. The required schema is included in filename with an abbreviation. I need a mapping between this abbreviation and the real schema name. What better way than an associative array, considering the actual schema names (not the abbreviation) may differ between environments, so an array variable (whose values can be set just once) is perfect

    – Slav
    Nov 19 '14 at 14:16






  • 2





    @Slav I'm not arguing against associative arrays, just against shell scripts where such complexity is needed. But that's just my personal preference; I often catch myself starting to write a shell script and then immediately rewriting it in Perl when I realize that I'm exceeding a certain complexity threshold.

    – Martin von Wittich
    Nov 19 '14 at 22:50














  • 5





    If you're trying to use associative arrays in a shell script it could be possible that your project is too complex for a shell script :)

    – Martin von Wittich
    Jan 29 '14 at 0:09











  • @MartinvonWittich why? I have a shell script that executes a SQL script on one of 3 possible DB schemas. The required schema is included in filename with an abbreviation. I need a mapping between this abbreviation and the real schema name. What better way than an associative array, considering the actual schema names (not the abbreviation) may differ between environments, so an array variable (whose values can be set just once) is perfect

    – Slav
    Nov 19 '14 at 14:16






  • 2





    @Slav I'm not arguing against associative arrays, just against shell scripts where such complexity is needed. But that's just my personal preference; I often catch myself starting to write a shell script and then immediately rewriting it in Perl when I realize that I'm exceeding a certain complexity threshold.

    – Martin von Wittich
    Nov 19 '14 at 22:50








5




5





If you're trying to use associative arrays in a shell script it could be possible that your project is too complex for a shell script :)

– Martin von Wittich
Jan 29 '14 at 0:09





If you're trying to use associative arrays in a shell script it could be possible that your project is too complex for a shell script :)

– Martin von Wittich
Jan 29 '14 at 0:09













@MartinvonWittich why? I have a shell script that executes a SQL script on one of 3 possible DB schemas. The required schema is included in filename with an abbreviation. I need a mapping between this abbreviation and the real schema name. What better way than an associative array, considering the actual schema names (not the abbreviation) may differ between environments, so an array variable (whose values can be set just once) is perfect

– Slav
Nov 19 '14 at 14:16





@MartinvonWittich why? I have a shell script that executes a SQL script on one of 3 possible DB schemas. The required schema is included in filename with an abbreviation. I need a mapping between this abbreviation and the real schema name. What better way than an associative array, considering the actual schema names (not the abbreviation) may differ between environments, so an array variable (whose values can be set just once) is perfect

– Slav
Nov 19 '14 at 14:16




2




2





@Slav I'm not arguing against associative arrays, just against shell scripts where such complexity is needed. But that's just my personal preference; I often catch myself starting to write a shell script and then immediately rewriting it in Perl when I realize that I'm exceeding a certain complexity threshold.

– Martin von Wittich
Nov 19 '14 at 22:50





@Slav I'm not arguing against associative arrays, just against shell scripts where such complexity is needed. But that's just my personal preference; I often catch myself starting to write a shell script and then immediately rewriting it in Perl when I realize that I'm exceeding a certain complexity threshold.

– Martin von Wittich
Nov 19 '14 at 22:50










4 Answers
4






active

oldest

votes


















19














Shells with associative arrays



Some modern shells provide associative arrays: ksh93, bash ≥4, zsh. In ksh93 and bash, if a is an associative array, then "${!a[@]}" is the array of its keys:



for k in "${!a[@]}"; do
echo "$k -> ${a[$k]}"
done


In zsh, that syntax only works in ksh emulation mode. Otherwise you have to use zsh's native syntax:



for k in "${(@k)a}"; do
echo "$k -> $a[$k]"
done


${(k)a} also works if a does not have an empty key.



In zsh, you could also loop on both keys and values at the same time:



for k v ("${(@kv)a}") echo "$k -> $v"


Shells without associative arrays



Emulating associative arrays in shells that don't have them is a lot more work. If you need associative arrays, it's probably time to bring in a bigger tool, such as ksh93 or Perl.



If you do need associative arrays in a mere POSIX shell, here's a way to simulate them, when keys are restricted to contain only the characters 0-9A-Z_a-z (ASCII digits, letters and underscore). Under this assumption, keys can be used as part of variable names. The functions below act on an array identified by a naming prefix, the “stem”, which must not contain two consecutive underscores.



## ainit STEM
## Declare an empty associative array named STEM.
ainit () {
eval "__aa__${1}=' '"
}
## akeys STEM
## List the keys in the associatve array named STEM.
akeys () {
eval "echo "$__aa__${1}""
}
## aget STEM KEY VAR
## Set VAR to the value of KEY in the associative array named STEM.
## If KEY is not present, unset VAR.
aget () {
eval "unset $3
case $__aa__${1} in
*" $2 "*) $3=$__aa__${1}__$2;;
esac"
}
## aset STEM KEY VALUE
## Set KEY to VALUE in the associative array named STEM.
aset () {
eval "__aa__${1}__${2}=$3
case $__aa__${1} in
*" $2 "*) :;;
*) __aa__${1}="${__aa__${1}}$2 ";;
esac"
}
## aunset STEM KEY
## Remove KEY from the associative array named STEM.
aunset () {
eval "unset __aa__${1}__${2}
case $__aa__${1} in
*" $2 "*) __aa__${1}="${__aa__${1}%%* $2 } ${__aa__${1}#* $2 }";;
esac"
}


(Warning, untested code. Error detection for syntactically invalid stems and keys is not provided.)






share|improve this answer

































    5














    I'm not sure what you mean by store, but you can iterate over the keys using the ${!array[@]} syntax:



    $ typeset -A foo=([key1]=bar [key2]=baz);
    $ echo "${!foo[@]}"
    key2 key1


    So, to iterate:



    $ for key in "${!foo[@]}"; do echo "$key : ${foo[$key]}"; done
    key2 : baz
    key1 : bar


    I found a nice, short tutorial on this here.





    As pointed out in the comments below, associative arrays were added in bash version 4. See here for a Linux journal article on the subject.






    share|improve this answer





















    • 1





      (bash version 4 only) That's an important thing to note. Traditionally, bash arrays are numeric only.

      – Ricky Beam
      Jan 28 '14 at 23:07






    • 1





      You might want to use typeset instead of declare in your examples. That would make them portable between bash 4 and ksh93 which first implemented shell associative arrays.

      – jlliagre
      Jan 29 '14 at 1:00



















    0














    Shells without associative arrays



    It's not that hard when keys are restricted to [0-9A-Za-z_] (numbers, letters, underscore).



    The trick is instead of storing to array[$key], store to variables array_$key.



    Set:



    eval "array_$key='$value'"


    Get:



    value=`eval echo '$'array_$key`


    Note: Values cannot contain ' (single quote).






    share|improve this answer

































      -1














      this works in bash



      cert="first"
      web="second"
      declare -A assoc_array=(["cert"]="${cert}" ["web"]="${web}")
      echo "first is" ${assoc_array[cert]}
      echo "second is" ${assoc_array[web]}


      OR



      #loop
      for i in "${assoc_array[@]}"
      do
      echo "$i"
      done


      No need to use eval afaik






      share|improve this answer








      New contributor




      JamesD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





















      • I believe that you've missed the point of the question.

        – G-Man
        4 hours ago











      Your Answer








      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "106"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f111397%2fassociative-arrays-in-shell-scripts%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      19














      Shells with associative arrays



      Some modern shells provide associative arrays: ksh93, bash ≥4, zsh. In ksh93 and bash, if a is an associative array, then "${!a[@]}" is the array of its keys:



      for k in "${!a[@]}"; do
      echo "$k -> ${a[$k]}"
      done


      In zsh, that syntax only works in ksh emulation mode. Otherwise you have to use zsh's native syntax:



      for k in "${(@k)a}"; do
      echo "$k -> $a[$k]"
      done


      ${(k)a} also works if a does not have an empty key.



      In zsh, you could also loop on both keys and values at the same time:



      for k v ("${(@kv)a}") echo "$k -> $v"


      Shells without associative arrays



      Emulating associative arrays in shells that don't have them is a lot more work. If you need associative arrays, it's probably time to bring in a bigger tool, such as ksh93 or Perl.



      If you do need associative arrays in a mere POSIX shell, here's a way to simulate them, when keys are restricted to contain only the characters 0-9A-Z_a-z (ASCII digits, letters and underscore). Under this assumption, keys can be used as part of variable names. The functions below act on an array identified by a naming prefix, the “stem”, which must not contain two consecutive underscores.



      ## ainit STEM
      ## Declare an empty associative array named STEM.
      ainit () {
      eval "__aa__${1}=' '"
      }
      ## akeys STEM
      ## List the keys in the associatve array named STEM.
      akeys () {
      eval "echo "$__aa__${1}""
      }
      ## aget STEM KEY VAR
      ## Set VAR to the value of KEY in the associative array named STEM.
      ## If KEY is not present, unset VAR.
      aget () {
      eval "unset $3
      case $__aa__${1} in
      *" $2 "*) $3=$__aa__${1}__$2;;
      esac"
      }
      ## aset STEM KEY VALUE
      ## Set KEY to VALUE in the associative array named STEM.
      aset () {
      eval "__aa__${1}__${2}=$3
      case $__aa__${1} in
      *" $2 "*) :;;
      *) __aa__${1}="${__aa__${1}}$2 ";;
      esac"
      }
      ## aunset STEM KEY
      ## Remove KEY from the associative array named STEM.
      aunset () {
      eval "unset __aa__${1}__${2}
      case $__aa__${1} in
      *" $2 "*) __aa__${1}="${__aa__${1}%%* $2 } ${__aa__${1}#* $2 }";;
      esac"
      }


      (Warning, untested code. Error detection for syntactically invalid stems and keys is not provided.)






      share|improve this answer






























        19














        Shells with associative arrays



        Some modern shells provide associative arrays: ksh93, bash ≥4, zsh. In ksh93 and bash, if a is an associative array, then "${!a[@]}" is the array of its keys:



        for k in "${!a[@]}"; do
        echo "$k -> ${a[$k]}"
        done


        In zsh, that syntax only works in ksh emulation mode. Otherwise you have to use zsh's native syntax:



        for k in "${(@k)a}"; do
        echo "$k -> $a[$k]"
        done


        ${(k)a} also works if a does not have an empty key.



        In zsh, you could also loop on both keys and values at the same time:



        for k v ("${(@kv)a}") echo "$k -> $v"


        Shells without associative arrays



        Emulating associative arrays in shells that don't have them is a lot more work. If you need associative arrays, it's probably time to bring in a bigger tool, such as ksh93 or Perl.



        If you do need associative arrays in a mere POSIX shell, here's a way to simulate them, when keys are restricted to contain only the characters 0-9A-Z_a-z (ASCII digits, letters and underscore). Under this assumption, keys can be used as part of variable names. The functions below act on an array identified by a naming prefix, the “stem”, which must not contain two consecutive underscores.



        ## ainit STEM
        ## Declare an empty associative array named STEM.
        ainit () {
        eval "__aa__${1}=' '"
        }
        ## akeys STEM
        ## List the keys in the associatve array named STEM.
        akeys () {
        eval "echo "$__aa__${1}""
        }
        ## aget STEM KEY VAR
        ## Set VAR to the value of KEY in the associative array named STEM.
        ## If KEY is not present, unset VAR.
        aget () {
        eval "unset $3
        case $__aa__${1} in
        *" $2 "*) $3=$__aa__${1}__$2;;
        esac"
        }
        ## aset STEM KEY VALUE
        ## Set KEY to VALUE in the associative array named STEM.
        aset () {
        eval "__aa__${1}__${2}=$3
        case $__aa__${1} in
        *" $2 "*) :;;
        *) __aa__${1}="${__aa__${1}}$2 ";;
        esac"
        }
        ## aunset STEM KEY
        ## Remove KEY from the associative array named STEM.
        aunset () {
        eval "unset __aa__${1}__${2}
        case $__aa__${1} in
        *" $2 "*) __aa__${1}="${__aa__${1}%%* $2 } ${__aa__${1}#* $2 }";;
        esac"
        }


        (Warning, untested code. Error detection for syntactically invalid stems and keys is not provided.)






        share|improve this answer




























          19












          19








          19







          Shells with associative arrays



          Some modern shells provide associative arrays: ksh93, bash ≥4, zsh. In ksh93 and bash, if a is an associative array, then "${!a[@]}" is the array of its keys:



          for k in "${!a[@]}"; do
          echo "$k -> ${a[$k]}"
          done


          In zsh, that syntax only works in ksh emulation mode. Otherwise you have to use zsh's native syntax:



          for k in "${(@k)a}"; do
          echo "$k -> $a[$k]"
          done


          ${(k)a} also works if a does not have an empty key.



          In zsh, you could also loop on both keys and values at the same time:



          for k v ("${(@kv)a}") echo "$k -> $v"


          Shells without associative arrays



          Emulating associative arrays in shells that don't have them is a lot more work. If you need associative arrays, it's probably time to bring in a bigger tool, such as ksh93 or Perl.



          If you do need associative arrays in a mere POSIX shell, here's a way to simulate them, when keys are restricted to contain only the characters 0-9A-Z_a-z (ASCII digits, letters and underscore). Under this assumption, keys can be used as part of variable names. The functions below act on an array identified by a naming prefix, the “stem”, which must not contain two consecutive underscores.



          ## ainit STEM
          ## Declare an empty associative array named STEM.
          ainit () {
          eval "__aa__${1}=' '"
          }
          ## akeys STEM
          ## List the keys in the associatve array named STEM.
          akeys () {
          eval "echo "$__aa__${1}""
          }
          ## aget STEM KEY VAR
          ## Set VAR to the value of KEY in the associative array named STEM.
          ## If KEY is not present, unset VAR.
          aget () {
          eval "unset $3
          case $__aa__${1} in
          *" $2 "*) $3=$__aa__${1}__$2;;
          esac"
          }
          ## aset STEM KEY VALUE
          ## Set KEY to VALUE in the associative array named STEM.
          aset () {
          eval "__aa__${1}__${2}=$3
          case $__aa__${1} in
          *" $2 "*) :;;
          *) __aa__${1}="${__aa__${1}}$2 ";;
          esac"
          }
          ## aunset STEM KEY
          ## Remove KEY from the associative array named STEM.
          aunset () {
          eval "unset __aa__${1}__${2}
          case $__aa__${1} in
          *" $2 "*) __aa__${1}="${__aa__${1}%%* $2 } ${__aa__${1}#* $2 }";;
          esac"
          }


          (Warning, untested code. Error detection for syntactically invalid stems and keys is not provided.)






          share|improve this answer















          Shells with associative arrays



          Some modern shells provide associative arrays: ksh93, bash ≥4, zsh. In ksh93 and bash, if a is an associative array, then "${!a[@]}" is the array of its keys:



          for k in "${!a[@]}"; do
          echo "$k -> ${a[$k]}"
          done


          In zsh, that syntax only works in ksh emulation mode. Otherwise you have to use zsh's native syntax:



          for k in "${(@k)a}"; do
          echo "$k -> $a[$k]"
          done


          ${(k)a} also works if a does not have an empty key.



          In zsh, you could also loop on both keys and values at the same time:



          for k v ("${(@kv)a}") echo "$k -> $v"


          Shells without associative arrays



          Emulating associative arrays in shells that don't have them is a lot more work. If you need associative arrays, it's probably time to bring in a bigger tool, such as ksh93 or Perl.



          If you do need associative arrays in a mere POSIX shell, here's a way to simulate them, when keys are restricted to contain only the characters 0-9A-Z_a-z (ASCII digits, letters and underscore). Under this assumption, keys can be used as part of variable names. The functions below act on an array identified by a naming prefix, the “stem”, which must not contain two consecutive underscores.



          ## ainit STEM
          ## Declare an empty associative array named STEM.
          ainit () {
          eval "__aa__${1}=' '"
          }
          ## akeys STEM
          ## List the keys in the associatve array named STEM.
          akeys () {
          eval "echo "$__aa__${1}""
          }
          ## aget STEM KEY VAR
          ## Set VAR to the value of KEY in the associative array named STEM.
          ## If KEY is not present, unset VAR.
          aget () {
          eval "unset $3
          case $__aa__${1} in
          *" $2 "*) $3=$__aa__${1}__$2;;
          esac"
          }
          ## aset STEM KEY VALUE
          ## Set KEY to VALUE in the associative array named STEM.
          aset () {
          eval "__aa__${1}__${2}=$3
          case $__aa__${1} in
          *" $2 "*) :;;
          *) __aa__${1}="${__aa__${1}}$2 ";;
          esac"
          }
          ## aunset STEM KEY
          ## Remove KEY from the associative array named STEM.
          aunset () {
          eval "unset __aa__${1}__${2}
          case $__aa__${1} in
          *" $2 "*) __aa__${1}="${__aa__${1}%%* $2 } ${__aa__${1}#* $2 }";;
          esac"
          }


          (Warning, untested code. Error detection for syntactically invalid stems and keys is not provided.)







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Feb 2 '16 at 13:27









          Stéphane Chazelas

          309k57584945




          309k57584945










          answered Jan 29 '14 at 0:48









          GillesGilles

          542k12810971616




          542k12810971616

























              5














              I'm not sure what you mean by store, but you can iterate over the keys using the ${!array[@]} syntax:



              $ typeset -A foo=([key1]=bar [key2]=baz);
              $ echo "${!foo[@]}"
              key2 key1


              So, to iterate:



              $ for key in "${!foo[@]}"; do echo "$key : ${foo[$key]}"; done
              key2 : baz
              key1 : bar


              I found a nice, short tutorial on this here.





              As pointed out in the comments below, associative arrays were added in bash version 4. See here for a Linux journal article on the subject.






              share|improve this answer





















              • 1





                (bash version 4 only) That's an important thing to note. Traditionally, bash arrays are numeric only.

                – Ricky Beam
                Jan 28 '14 at 23:07






              • 1





                You might want to use typeset instead of declare in your examples. That would make them portable between bash 4 and ksh93 which first implemented shell associative arrays.

                – jlliagre
                Jan 29 '14 at 1:00
















              5














              I'm not sure what you mean by store, but you can iterate over the keys using the ${!array[@]} syntax:



              $ typeset -A foo=([key1]=bar [key2]=baz);
              $ echo "${!foo[@]}"
              key2 key1


              So, to iterate:



              $ for key in "${!foo[@]}"; do echo "$key : ${foo[$key]}"; done
              key2 : baz
              key1 : bar


              I found a nice, short tutorial on this here.





              As pointed out in the comments below, associative arrays were added in bash version 4. See here for a Linux journal article on the subject.






              share|improve this answer





















              • 1





                (bash version 4 only) That's an important thing to note. Traditionally, bash arrays are numeric only.

                – Ricky Beam
                Jan 28 '14 at 23:07






              • 1





                You might want to use typeset instead of declare in your examples. That would make them portable between bash 4 and ksh93 which first implemented shell associative arrays.

                – jlliagre
                Jan 29 '14 at 1:00














              5












              5








              5







              I'm not sure what you mean by store, but you can iterate over the keys using the ${!array[@]} syntax:



              $ typeset -A foo=([key1]=bar [key2]=baz);
              $ echo "${!foo[@]}"
              key2 key1


              So, to iterate:



              $ for key in "${!foo[@]}"; do echo "$key : ${foo[$key]}"; done
              key2 : baz
              key1 : bar


              I found a nice, short tutorial on this here.





              As pointed out in the comments below, associative arrays were added in bash version 4. See here for a Linux journal article on the subject.






              share|improve this answer















              I'm not sure what you mean by store, but you can iterate over the keys using the ${!array[@]} syntax:



              $ typeset -A foo=([key1]=bar [key2]=baz);
              $ echo "${!foo[@]}"
              key2 key1


              So, to iterate:



              $ for key in "${!foo[@]}"; do echo "$key : ${foo[$key]}"; done
              key2 : baz
              key1 : bar


              I found a nice, short tutorial on this here.





              As pointed out in the comments below, associative arrays were added in bash version 4. See here for a Linux journal article on the subject.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jan 29 '14 at 2:23

























              answered Jan 28 '14 at 22:58









              terdonterdon

              132k32261441




              132k32261441








              • 1





                (bash version 4 only) That's an important thing to note. Traditionally, bash arrays are numeric only.

                – Ricky Beam
                Jan 28 '14 at 23:07






              • 1





                You might want to use typeset instead of declare in your examples. That would make them portable between bash 4 and ksh93 which first implemented shell associative arrays.

                – jlliagre
                Jan 29 '14 at 1:00














              • 1





                (bash version 4 only) That's an important thing to note. Traditionally, bash arrays are numeric only.

                – Ricky Beam
                Jan 28 '14 at 23:07






              • 1





                You might want to use typeset instead of declare in your examples. That would make them portable between bash 4 and ksh93 which first implemented shell associative arrays.

                – jlliagre
                Jan 29 '14 at 1:00








              1




              1





              (bash version 4 only) That's an important thing to note. Traditionally, bash arrays are numeric only.

              – Ricky Beam
              Jan 28 '14 at 23:07





              (bash version 4 only) That's an important thing to note. Traditionally, bash arrays are numeric only.

              – Ricky Beam
              Jan 28 '14 at 23:07




              1




              1





              You might want to use typeset instead of declare in your examples. That would make them portable between bash 4 and ksh93 which first implemented shell associative arrays.

              – jlliagre
              Jan 29 '14 at 1:00





              You might want to use typeset instead of declare in your examples. That would make them portable between bash 4 and ksh93 which first implemented shell associative arrays.

              – jlliagre
              Jan 29 '14 at 1:00











              0














              Shells without associative arrays



              It's not that hard when keys are restricted to [0-9A-Za-z_] (numbers, letters, underscore).



              The trick is instead of storing to array[$key], store to variables array_$key.



              Set:



              eval "array_$key='$value'"


              Get:



              value=`eval echo '$'array_$key`


              Note: Values cannot contain ' (single quote).






              share|improve this answer






























                0














                Shells without associative arrays



                It's not that hard when keys are restricted to [0-9A-Za-z_] (numbers, letters, underscore).



                The trick is instead of storing to array[$key], store to variables array_$key.



                Set:



                eval "array_$key='$value'"


                Get:



                value=`eval echo '$'array_$key`


                Note: Values cannot contain ' (single quote).






                share|improve this answer




























                  0












                  0








                  0







                  Shells without associative arrays



                  It's not that hard when keys are restricted to [0-9A-Za-z_] (numbers, letters, underscore).



                  The trick is instead of storing to array[$key], store to variables array_$key.



                  Set:



                  eval "array_$key='$value'"


                  Get:



                  value=`eval echo '$'array_$key`


                  Note: Values cannot contain ' (single quote).






                  share|improve this answer















                  Shells without associative arrays



                  It's not that hard when keys are restricted to [0-9A-Za-z_] (numbers, letters, underscore).



                  The trick is instead of storing to array[$key], store to variables array_$key.



                  Set:



                  eval "array_$key='$value'"


                  Get:



                  value=`eval echo '$'array_$key`


                  Note: Values cannot contain ' (single quote).







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 6 '17 at 4:49

























                  answered Jan 6 '17 at 3:50









                  Marián ČernýMarián Černý

                  1677




                  1677























                      -1














                      this works in bash



                      cert="first"
                      web="second"
                      declare -A assoc_array=(["cert"]="${cert}" ["web"]="${web}")
                      echo "first is" ${assoc_array[cert]}
                      echo "second is" ${assoc_array[web]}


                      OR



                      #loop
                      for i in "${assoc_array[@]}"
                      do
                      echo "$i"
                      done


                      No need to use eval afaik






                      share|improve this answer








                      New contributor




                      JamesD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.





















                      • I believe that you've missed the point of the question.

                        – G-Man
                        4 hours ago
















                      -1














                      this works in bash



                      cert="first"
                      web="second"
                      declare -A assoc_array=(["cert"]="${cert}" ["web"]="${web}")
                      echo "first is" ${assoc_array[cert]}
                      echo "second is" ${assoc_array[web]}


                      OR



                      #loop
                      for i in "${assoc_array[@]}"
                      do
                      echo "$i"
                      done


                      No need to use eval afaik






                      share|improve this answer








                      New contributor




                      JamesD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.





















                      • I believe that you've missed the point of the question.

                        – G-Man
                        4 hours ago














                      -1












                      -1








                      -1







                      this works in bash



                      cert="first"
                      web="second"
                      declare -A assoc_array=(["cert"]="${cert}" ["web"]="${web}")
                      echo "first is" ${assoc_array[cert]}
                      echo "second is" ${assoc_array[web]}


                      OR



                      #loop
                      for i in "${assoc_array[@]}"
                      do
                      echo "$i"
                      done


                      No need to use eval afaik






                      share|improve this answer








                      New contributor




                      JamesD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.










                      this works in bash



                      cert="first"
                      web="second"
                      declare -A assoc_array=(["cert"]="${cert}" ["web"]="${web}")
                      echo "first is" ${assoc_array[cert]}
                      echo "second is" ${assoc_array[web]}


                      OR



                      #loop
                      for i in "${assoc_array[@]}"
                      do
                      echo "$i"
                      done


                      No need to use eval afaik







                      share|improve this answer








                      New contributor




                      JamesD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.









                      share|improve this answer



                      share|improve this answer






                      New contributor




                      JamesD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.









                      answered 4 hours ago









                      JamesDJamesD

                      1




                      1




                      New contributor




                      JamesD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.





                      New contributor





                      JamesD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.






                      JamesD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.













                      • I believe that you've missed the point of the question.

                        – G-Man
                        4 hours ago



















                      • I believe that you've missed the point of the question.

                        – G-Man
                        4 hours ago

















                      I believe that you've missed the point of the question.

                      – G-Man
                      4 hours ago





                      I believe that you've missed the point of the question.

                      – G-Man
                      4 hours ago


















                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Unix & Linux Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f111397%2fassociative-arrays-in-shell-scripts%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Loup dans la culture

                      How to solve the problem of ntp “Unable to contact time server” from KDE?

                      ASUS Zenbook UX433/UX333 — Configure Touchpad-embedded numpad on Linux