Looping through array variable in Bash
Are you a Bash enthusiast looking to iterate over items in an array variable? Look no further! In this quick guide, we'll explore how to loop through array variables in Bash and provide a practical example of using the for loop.
The Basics
In Bash, arrays are declared by assigning values to an indexed name. For instance, workspaces=(dev stg pro)
creates an array called workspaces with three elements: "dev", "stg", and "pro". To iterate over these elements, we can use the for loop.
The Code
Here's a simple example of how to loop through an array variable in Bash:
dir=$(pwd)
workspaces=(dev stg pro)
for ws in "${workspaces[@]}"
do
echo "Workspace- ${ws}:"
terraform workspace select ${ws}
output="${dir}/resources_${ws}.txt"
terraform state list >> ${output}
done
In this example, we're iterating over the workspaces array and performing some actions for each element. The ${workspaces[@]}
syntax is used to expand the array into individual elements.
Example: Listing Terraform Resources
When we run the above code, Bash will execute the loop once for each element in the workspaces array. For each iteration:
- It sets the value of ws to the current element in the array.
- It prints a message indicating which workspace is being processed.
- It selects the corresponding Terraform workspace using
terraform workspace select
.
- It generates a list of Terraform resources using
terraform state list
on the workspace to an output file with the name resources_<workspace_name>.txt.
Conclusion
In this quick guide, we've seen how to iterate over items in an array variable in Bash using the for loop. With this knowledge, you can now write more efficient and effective scripts for automating tasks in your terminal.
Remember to replace the Terraform commands with your own actions or logic to suit your specific needs. Happy scripting!