0

I have two arrays in a bash script say

ConfigA=("hostname1" "hostname2")
ConfigB=("hostname3" "hostname4")

Now I am passing an argument to the script specifying which Array I need to work with

For that I came up with a bash equivalent of ternary operator like below

int a = (b == 5) ? c : d;

equilvalent in bash

a=$([ "$b" == 5 ] && echo "$c" || echo "$d")

I tried to use this in my case as follows

env=$1
Config=$([ "$env" == "qa" ]] && echo "${ConfigA[@]}" || echo "${ConfigB[@]}")

However in the above case I get the output

hostname1 hostname2

but Its not an array, since when I try to loop over it, it print both at once.

I have also tried to surround the array within () like

Config=$([ "$env" == "qa" ]] && echo "( ${ConfigA[@]} )" || echo "( ${ConfigB[@]} )")

but that also doesn't help.

How do I assign the array to a new variable with a ternary operator?

I understand I can do it with a if-else condition, but I would like to do it with ternary operator

Thanks for any help

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400

2 Answers2

0

So instead of having () within quotes in the second case, another approach to assign array to a variable like

[ "$env" == "qa" ]] && Config=( "${ConfigA[@]}" ) || Config( "${ConfigB[@]}" )

works

What happened in

Config=$([ "$env" == "qa" ]] && echo "( ${ConfigA[@]} )" || echo "( ${ConfigB[@]} )")

was that echo converted the array to a string and appended the () around it and hence it did not work

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

There is no simple way to copy array from a variable to another in bash.

According to this Bash: How to assign an associative array to another variable name (e.g. rename the variable)?, a workaround you could use is the following:

[[ "$env" == "qa" ]] && eval $(declare -p ConfigA | sed 's/ConfigA/Config/') || eval $(declare -p ConfigB | sed 's/ConfigB/Config/')
echo ${Config[*]}
hostname3 hostname4
Community
  • 1
  • 1
oliv
  • 12,690
  • 25
  • 45
  • And what if the source array's name is contained in it as an element or a substring thereof, e.g. `x=(x y z)` or `a=(abc def)` – Leon Feb 27 '17 at 09:18
  • @Leon in that case best is to loop over all elements of the array, as suggested in the link I mentioned – oliv Feb 27 '17 at 09:22