Home > Back-end >  Store output of shell command with multiple arguments into an array
Store output of shell command with multiple arguments into an array

Time:02-11

I'm trying to store the states of my terraform workspaces in an array using shell.

I'm trying this way which usually works for me:

declare -a workspace_list=( $(terraform workspace list))

for a in $(seq 0 ${#workspace_list[*]})
do  
    if [[ -z ${workspace_list[$a]} ]]
        then  
              break
        fi
    echo $(($a 1))": "${workspace_list[$a]}
    a=$(($a 1))
done

However, it gives me an output with all the files in the directory as well along with the workspaces.

I'm guessing it's to do with the multiple args with terraform command. Please help.

Output of terraform workspace list for reference enter image description here

CodePudding user response:

When you initialize the array with the result of terraform command it looks like:

declare -a workspace_list=( * default dev-singapore)

Here, * is glob-expanded to list of all files in current directory.

You can get rid of the asterisk just processing terraform's output.

declare -a workspace_list=($(terraform workspace list | sed 's/*//'))

Unfortunately unlike terraform plan, there is no option for JSON output from terraform workspace, which would be more clean.

  • Related