Bash Script Terraform Workspace List

When I run terraform workspace list I got:
❯ terraform workspace list

  • default
    test

But if I run like this echo $(terraform workspace list) I also got the list of files in the current folder:

main.tf api.tf modules README.md terraform.tfvars.example test.tfvars variables.tf default test

Why does this happen?

Thanks for the support.

That happens because the output of terraform workspace list has a wildcard in it:

$ terraform workspace list
* default

That output is being passed to echo and the shell is expanding the wildcard:

$ echo *
main.tf api.tf modules README.md terraform.tfvars.example test.tfvars variables.tf default test

If you don’t want the shell to expand the wildcard, you have to quote everything:

$ echo "$(terraform workspace list)"
* default

I suggest using ShellCheck, as it’ll warn you about these things.

3 Likes

Many Thanks @gtirloni

Hi @gtirloni,

There is a way to use the command directly in a loop?

for i in "$(terraform workspace list)"; do echo $i; done

Because in the For i continue receive all files.
I solve my problem using a file, but i would like know if is possible do this without creating a temporary files.

Try something like:

for i in "$(terraform workspace list | awk '{print $2}')"; do echo $i; done

Thanks @gtirloni one more time

for i in $(terraform workspace list|sed 's/*//g'); do echo "linia $i"; done

Or like this