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
HH=1
ARR=(
"a"
"b"
"c"
)
if [[ ${HH} == 1 ]]; then
ARR+=("f")
else
ARR+=("g")
if
ARR+=(
"d"
"e"
)
In case there is only if part the array contains an empty string element. How do I fix that? For e.g; "$(if [ "${HH}" = 1 ]; then echo "d"; fi)", this adds an empty string element to the array if HH=0
If you are fine with ignoring shellcheck error https://www.shellcheck.net/wiki/SC2046 , then remove the quotes around the $(..) expression. Unquoted command substition will result in executing word splitting (and filename expansion) over the result, effectively replacing an empty string with no words resulting in no items. However this might not work with a string with spaces, * ? [ characters in the resulting string. In such cases, use other presented method. See also https://mywiki.wooledge.org/WordSplitting , https://www.gnu.org/software/bash/manual/html_node/Shell-Expansions.html .
HH=1
ARR=(
"a"
"b"
"c"
$(if [[ ${HH} == 1 ]]; then echo f; fi)
"d"
"e"
# pitfalls:
$(if [[ ${HH} == 1 ]]; then echo "a b c"; fi) # adds 3 elements
$(if [[ ${HH} == 1 ]]; then echo "'a b c'"; fi) # also adds 3 elements, it is just not possible to quote "inside"
$(if [[ ${HH} == 1 ]]; then echo "*"; fi) # expands *, adds all files in PWD
)
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.