This page is READ-ONLY. It is generated from the old site.
All timestamps are relative to 2013 (when this page is generated).
If you are looking for TeX support, please go to VietTUG.org

Associated array in Bash :)

Bash 4 cool
Added by ruby about 1 year ago  »  Votes: 2/2

Bash 4 supports associated array (similar to "Hash" in Ruby or "Dictionary" in Python). Here is simple example

 1 # First, you declare your array. You must use "-A", not "-a" 
 2 declare -A MYASSOC
 3 
 4 # Now you can add new entry to the array
 5 MYASSOC["foo"]=$((12*13))
 6 MYASSOC["foo.bar"]="This is a test" 
 7 
 8 # To get an value at some index, try ${}
 9 echo "The associated value of "foo.bar" is ${MYASSOC["foo.bar"]}" 
10 
11 # You can use a variable name as index. Note at the quotation
12 my_index="foo.bar" 
13 echo "The associcated value is ${MYASSOC[$my_index]}" 

The associated array is very cool support. It would be useful when you want to write some Bash script that has a dynamic / modulable / loadable configuration. For example, when you write a jifty script to set quota for all FTP users on the system, you need a seperated file to store the quota table (instead of provide hard-code to support quota setting for each users). If the script is my_script.sh, the configuration my_script.sh.conf would be

1 # Clearly these information shouldn't put in the main script my_script.sh
2 _QUOTA["user_1"]=$((1*$_GB_in_Bytes))
3 _QUOTA["user_2"]=$((2*$_GB_in_Bytes))
4 _QUOTA["user_3"]=$((3*$_GB_in_Bytes))

Comments