Q: Bash script does not find index from array I have written a bash script which I want to use to monitor backups on a synology via pushgateway.
The script should search for subfolders in the backup folder, write the newest file into a variable and write the age and size of the file into an array.
To give it finally to the push gateway, I list all metrics with indexes. All folders or files are available. If I execute the script, often one or more indexes are not found. If I execute the commands manually one by one, I get a correct output.
Here is the script:
#!/bin/bash
set -e

backup_dir=$1

for dir in $(find "$backup_dir" -maxdepth 1 -mindepth 1 -type d \( ! -name @eaDir \)); do
    if compgen -G "${dir}/*.vib" > /dev/null; then
        latest_vib=$(ls -t1 "$dir"/*.vib | head -1)
        age_vib=$(( ( $(date +%s) - $(stat -c %Y "$latest_vib") ) ))
        size_vib=$(stat -c %s "$latest_vib")

        arrage_vib+=("${age_vib}")
        arrsize_vib+=("${size_vib}")
    fi
    if compgen -G "${dir}/*.vbk" > /dev/null; then
        latest_vbk=$(ls -t1 "$dir"/*.vbk | head -1)
        age_vbk=$(( ( $(date +%s) - $(stat -c %Y "$latest_vbk") ) ))
        size_vbk=$(stat -c %s "$latest_vbk")

        arrage_vbk+=("${age_vbk}")
        arrsize_vbk+=("${size_vbk}")
    fi

    min_dir=$(echo "$dir" | cut -d'/' -f4- | tr '[:upper:]' '[:lower:]')
    sign_dir=${min_dir//_/-}
    arrdir+=("${sign_dir}")
done

echo "${arrdir[4]}"
echo "${arrage_vib[4]}"

cat << EOF | curl -ks -u user:pw --data-binary @- https://pushgateway/metrics/job/backup/instance/instance_name
    # HELP backup_age displays the age of backups in seconds
    # TYPE backup_age gauge
    backup_age_vib{dir="${arrdir[1]}"} ${arrage_vib[1]}
    backup_age_vib{dir="${arrdir[2]}"} ${arrage_vib[2]}
    backup_age_vib{dir="${arrdir[3]}"} ${arrage_vib[3]}
    backup_age_vib{dir="${arrdir[4]}"} ${arrage_vib[4]}
    backup_age_vbk{dir="${arrdir[1]}"} ${arrage_vbk[1]}
    ...
    # HELP backup_size displays the size of backups in bytes
    # TYPE backup_size gauge
    backup_size_vib{dir="${arrdir[1]}"} ${arrsize_vib[1]}
    ...
EOF

I hope you can help me and point out where I made a mistake. I am also open for general optimizations of the script, because I assume that it can be solved better and more performant or optimal. I have a few lines of code from here ;-).
Many thanks in advance.
