Last week I was working on a bash script for a project at work. The script parsed through a log file with server load and disk usage statistics at regular intervals. The script was calculating the average CPU idle time, disk utilization, and disk usage for servers. After calculating the averages for each of these three metrics, I then proceeded to loop through all the lines in the file and create an array of all the times when the CPU idle time was below average, or the disk utilization or usage was above average.

The code that I used was originally taken from the article Bash: Append to array using while-loop by Freddy Vulto. The concept that Freddy used is essentially the same as what I was doing. I was using a for loop to scan a file, and if certain values in the file met a condition, the date was added to an array which was printed at the end of the script execution. The code to achieve this is as follows:

array=( ${array[@]-} $(echo "$variable") )

The code above reads as follows:

array=( ….. ) : Set your array variable named, appropriately enough: array.

${array[@]-} : Read all variables from the array array. The hyphen at the end prevents an “unbound variable” error when -u or -o nounset is set and array is an empty array. This is useful for appending the first value to an empty array in the event that one of the aforementioned flags is set.

$(echo “$variable”) : Add the variable $variable to the array through the use of command substitution $(…) by reading the output of echo “$variable” as the input value for the array. The reason for command substitution is that if you try it without the $(…), bash will read echo and “$variable” as separate entries into the array instead of just the value of $variable

Check out these Related Posts