Bash script (bashmap): A quasi-bash function without hashmap

Source: Internet
Author: User

@ 2013/7/19

-Added the bashmap_clear command to delete the key or clear the entire map.

Step 1: add the function to the bash script (or. bashrc)

# for bashmap {# echo md5 code for $1md5(){  if [ X"$1" == X"" ]  then    echo ""  else    echo "$1" | md5sum - | cut -c 1-32  fi}# Usage#   > bashmap "key" "value"  # set map[key] = value.#   > bashmap "key"          # print map[key]bashmap(){  WX_BASHMAP_PREFIX="BASHMAP_"  export WX_BASHMAP_PREFIX  md5key=$(eval "md5 '$1'")  case "$#" in  1)    eval "echo \$$WX_BASHMAP_PREFIX$md5key"    ;;  2)    eval "export $WX_BASHMAP_PREFIX$md5key='$2'"    ;;  *)    echo 'Usage:'    echo '   bashmap "key" "value"'    echo '   bashmap "key"'    ;;  esac}# Usage:#    > bashmap_clear      # clear All map items#    > bashmap_clear Key  # clear a map time by Keybashmap_clear(){  WX_BASHMAP_PREFIX="BASHMAP_"  export WX_BASHMAP_PREFIX  case "$#" in  0)    for env in $(set | grep "^$WX_BASHMAP_PREFIX" | cut -d'=' -f1)    do      unset $env    done    ;;  1)    md5key=$(eval "md5 '$1'")    unset $WX_BASHMAP_PREFIX$md5key    ;;  esac}# for bashmap }

Step 2: Use bashmap to set key: Value

> bashmap A "Value for A"> bashmap B "Value for B"> bashmap "A B" "Value for A B"

Step 3: Use bashmap to obtain the value corresponding to the key. If no preset key exists, an empty string "" is returned ""

> bashmap AValue for A> bashmap BValue for B> bashmap "A B"Value for A B

Step 4: delete a specified key

> bashmap_clear "B"

Step 5: Clear the map

> bashmap_clear

Have fun!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.