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

156 views Asked by At

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.

2

There are 2 answers

0
tshiono On BEST ANSWER

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.

1
Alex Maina On

I hope i have understood your question well. In python you can write the following code

sites=[
    ("site1", "/var/www/webroot1"),
    ("site2", "/var/www/webroot2"),
    ("site3", "/var/www/webroot3")
]
##create a dictionary called arr{} with key: site and value:webroot
arr = {}
for k,v in sites:
    if k in arr:
        arr[k].append(v)
    else:
        arr[k] = v
print(arr)

The output will be:

{'site1': '/var/www/webroot1', 'site2': '/var/www/webroot2', 'site3': '/var/www/webroot3'}

You can now manipulate the dictionary arr{} above as you wish.

To execute the command borg create --verbose --progress --list --stats --show-rc --compression lz4 $REPOSITORY::{$key}-{now:%Y-%m-%d} $valuethen you need to loop through the dictionery arr{} like so:

for k,v in arr.items():
   borg create --verbose --progress --list --stats --show-rc --compression lz4 $REPOSITORY::{k}-{now:%Y-%m-%d} v

I have replaced {site} with {k} and /var/www/webroot with v in the borg create command.