How Can I Iterate Over Arrays in Multiple Files with Bash?
Asked by
TechieNinja42
I'm working on a bash script where I have a series of text files, each containing an array of the same length. I want the script to loop through the folder with these files and read each file to update a variable based on specific elements in the arrays. For example, I want to sum up the first elements of each array, so that my variable `a` is the total of all `arr[0]` values across all files. To clarify, the files contain server usage data, like `0 45 55 569 677 1200`, meaning each file has server usage data but in different formats. I need this variable to assist with auto-scaling functionalities in my project. Here's what I have so far in my script:
Answers
It looks like you're having trouble with how you're iterating through the arrays. In your loop, instead of using `for j in "${numbers[@]}"; do val="${numbers[$j]}"`, try using `for val in "${numbers[@]}"; do`. This way, `val` will take each element directly without needing to use it as an index. If you need the index later, you can use `for index in "${!numbers[@]}"; do val="${numbers[$index]}"` to get both the index and the value. Give that a shot!
Reply to this answer
I noticed another potential hiccup in your approach. The line `file=( *.txt )` may not behave as you expect if there are no `.txt` files in the directory. Itโs a good idea to ensure that your script handles cases where no files are found. Using `shopt -s nullglob` will handle that for you if you want to avoid issues. Good luck with your project!
Reply to this answer
Add your answer
Answers are reviewed before publication.
ArrayMaster99: Yeah, definitely check that! Also, don't forget to set `shopt -s nullglob` at the beginning of your script. This will help if there are no matching files, so you won't run into issues with the glob storing literally as an empty string.