bashkey-valuebash4

How to use key and value in a `borg create` command using for loop(or not)


I have some sites on a server and I want to only backup their webroots creating a new repository for each site. With bash 4 I can use a dictionary.

declare -A sites=(["site1"]="/var/www/webroot1"
                  ["site2"]="/var/www/webroot2"
                  ["site3"]="/var/www/webroot3"
                  )

The borg command is:

borg create  --verbose  --progress --list --stats  --show-rc  --compression lz4 $REPOSITORY::{$key}-{now:%Y-%m-%d} $value

How can I create a for loop that will use both key and value in this command? Something like the following but instead doing echo, use the keys and values in the command and backup all sites one by one.

for i in "${!projects[@]}";
do
  echo "key  : $i"
  echo "value: ${sites[$i]}"
done

I don't want to just echo the key and value. I want to use them in one command.


Solution

  • I hope this is what you want:

    declare -A sites=(["site1"]="/var/www/webroot1"
                      ["site2"]="/var/www/webroot2"
                      ["site3"]="/var/www/webroot3"
                      )
    
    for key in "${!sites[@]}"; do
        borg create --verbose --progress --list --stats --show-rc --compression lz4 "$REPOSITORY"::{"$key"}-{now:%Y-%m-%d} "${sites[$key]}"
    done
    

    It assumes the variable REPOSITORY is also defined to some value.