Stanislav Hosek
Stanislav Hosek

Reputation: 37

Bash, read variable with variable inside

I have a script.

style_header[true]="background-color: rgb(230,250,230);"
style_header[false]="background-color: rgb(250,230,230);"

if COMMAND; then
    export=true
else
    export=false
fi

echo "${style_header[$export]}"

COMMAND finished ok, so export=true, but it returns style_header[false] variable "background-color: rgb(250,230,230);".

background-color: rgb(250,230,230);

I need to return this.

background-color: rgb(230,250,230);

It works with number 0 or 1 as index, but I need 'true' or 'false' variable inside.

Is possible to do that? I mean set array index as variable.

Upvotes: 1

Views: 150

Answers (1)

Barmar
Barmar

Reputation: 780673

Use declare -A style_array to declare it as an associative array. By default it's assumed to be an indexed array.

#!/bin/bash

declare -A style_header
style_header[true]="background-color: rgb(230,250,230);"
style_header[false]="background-color: rgb(250,230,230);"

if COMMAND; then
export=true
else
export=false
fi

echo "${style_header[$export]}"

DEMO

Upvotes: 3

Related Questions