0

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.

Vasiliki
  • 143
  • 9

2 Answers2

0

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.

Alex Maina
  • 296
  • 3
  • 11
  • I need to execute the command `borg create --verbose --progress --list --stats --show-rc --compression lz4 $REPOSITORY::{$key}-{now:%Y-%m-%d} $value`. I don't need to just print or echo the keys and values, I am trying to use them as variables. I need to do `borg create --verbose --progress --list --stats --show-rc --compression lz4 $REPOSITORY::{site}-{now:%Y-%m-%d} /var/www/webroot` . How can this be done for all keys and values in the dictionary? – Vasiliki Dec 16 '19 at 14:01
0

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.

tshiono
  • 21,248
  • 2
  • 14
  • 22