1

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.

1
  • By default, style_header is an indexed array, so things like style_header[true] are processed by treating the index as an arithmetic expression. Since neither true nor false is defined as a variable, they both evaluate to 0. So style_header[true] and style_header[false] are both equivalent to style_header[0]. Commented Jun 11, 2019 at 21:43

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect! Thank you very much! I tried it with declare before, but I did something wrong.
Maybe you used -a instead of -A?
Yes, it could be the problem. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.