1

I'm modifying a simple script to add function and learn more about how to write bash scripts. Currently, the script creates associative arrays using a function:

declare -A site theme
add_site() {
    local shortcut=$1
    site[$shortcut]=$2
    theme[$shortcut]=$3
}
add_site x1 example1.com alpha
add_site x2 example2.com beta

Now I'd like it to read an ini file for the variables. However, the documentation I've come across all instruct how to source the file, but only uses single arrays for examples. How do I create the arrays using a data file that looks like the following to make an associative array:

[site1]
shortcut=x1
site=example1.com
theme=alpha

[site2]
shortcut=x2
site=example2.com
theme=beta

1 Answer 1

2

You can do this:

#!/bin/bash

declare -A site=() theme=()

add_site() {
    local shortcut=$1
    site[$shortcut]=$2
    theme[$shortcut]=$3
}

while IFS= read -r line; do
    case "$line" in
    shortcut=*)
        # IFS== read -r __ shortcut <<< "$line"
        _shortcut=${line#*=}
        ;;
    site=*)
        # IFS== read -r __ site <<< "$line"
        _site=${line#*=}
        ;;
    theme=*)
        # IFS== read -r __ theme <<< "$line"
        _theme=${line#*=}
        add_site "$_shortcut" "$_site" "$_theme"
        ;;
    esac
done < file.ini

Test output with added echo "$@" on function:

x1 example1.com alpha
x2 example2.com beta
7
  • When I test the output I only get the first set of variables. Using for loop to iterate I can see a zero value for the second key in the site array.
    – dimmech
    Commented Aug 12, 2014 at 18:10
  • @user1074170 I used local names same to the array variable names sorry. I made an update.
    – konsolebox
    Commented Aug 12, 2014 at 18:18
  • I don't see the zero value key anymore but it seems to be only storing the first set of values.
    – dimmech
    Commented Aug 12, 2014 at 18:33
  • @user1074170 It works well on my test. Can you show debug output? (bash -x script.sh)
    – konsolebox
    Commented Aug 12, 2014 at 18:34
  • 1
    No it's not the default, but that worked! Thanks a heap.
    – dimmech
    Commented Aug 12, 2014 at 19:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .