1

In the below shell script, I'm trying to conditionally add elements to an array which is syntactically incorrect when checked in shellcheck.

#!/bin/bash

echo "Hello World";
HH=1

ARR=(
    "a"
    "b"
    "c"
    if [ ${HH} = 1 ]; then
        "f"
    else
        "g"
    fi
    "d"
    "e"
)

for arr in "${ARR[@]}"; do
    echo "${arr}"
done

ShellCheck Error:

Line 6:
ARR=(
^-- SC1009 (info): The mentioned syntax error was in this variable assignment.
    ^-- SC1073 (error): Couldn't parse this array assignment. Fix to allow more checks.
 
Line 12:
    if [ ${HH} = 1 ]; then
                    ^-- SC1072 (error): Expected ) to close array assignment. Fix any mentioned problems and try again.
0

2 Answers 2

4

Keep it simple and set a variable to the value you want to use in the array:

if [[ "$HH" == 1 ]]; then
    foo="f"
else
    foo="g"
fi

ARR=(
    "a"
    "b"
    "c"
    "$foo"
    "d"
    "e"
)
Sign up to request clarification or add additional context in comments.

1 Comment

It's worth noting that this is much more efficient than the subshell in the other answer's first example (which forks off a subprocess to run the if)
2

How to conditionally add elements to an array in shell script

Here are some examples:

HH=1
ARR=(
    "a"
    "b"
    "c"
    "$(if [[ ${HH} == 1 ]]; then echo f; else echo g; fi)"
    "d"
    "e"
)
HH=1
lookup=([0]=g [1]=f)
ARR=(
    "a"
    "b"
    "c"
    "${lookup[HH]}"
    "d"
    "e"
)
HH=1
ARR=(
    "a"
    "b"
    "c"
    "d"
    "e"
)
if [[ ${HH} == 1 ]]; then
   ARR+=(f)
else
   ARR+=(g)
if
# insert element $3 at position $2 in array $1
array_insert() {
    local -n _arr="$1" || return 2
    _arr=("${_arr[@]::$2}" "${@:3}" "${_arr[@]:$2}")
}
HH=1
ARR=(
    "a"
    "b"
    "c"
    "d"
    "e"
)
if [[ ${HH} == 1 ]]; then
   array_insert ARR 3 f
else
   array_insert ARR 3 g
if

There is no need to do if [ ! ${#ARR[@]} -eq 0 ]; then. When array is empty, "${ARR[@]}" is nothing, so the loop will not run at all.

2 Comments

Why not use lookup=(g f) instead of lookup=([0]=g [1]=f)
There is no reason.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.