外部iniファイルの変数に連想配列を追加するには?

外部iniファイルの変数に連想配列を追加するには?

機能を追加し、bashスクリプトを作成する方法の詳細については、単純なスクリプトを修正しています。現在のスクリプトは関数を使用して連想配列を生成します。

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

さて、変数のiniファイルを読みたいです。しかし、私が見た文書はすべてファイルをインポートする方法を示していますが、単一の配列のみを例として使用します。連想配列を生成するために、以下のデータファイルを使用して配列を生成する方法:

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

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

ベストアンサー1

次のことができます。

#!/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

echo "$@"機能テスト出力に追加:

x1 example1.com alpha
x2 example2.com beta

おすすめ記事