0

I'm just barely familiar with bash scripts, and am trying to achieve being able to specify a source location (a directory with files / sub-directories) and a list of multiple destination directories, along with a list of files / directories from the source to exclude when copying & replacing.

The script should loop through each destination location, copy the files from the source and replace them in the destination location, excluding any files / directories listed in the script to skip.

In PHP it would be something like:

$source = '/home/user1/public_html';
$destinations = array(
    'user2',
    'user3',
    'user4'
);
$exclude = array(
    '/uploads/custom',
    '/config/conf.php'
);
foreach ($destinations as $destination) {
    $dir = '/home/' .$destination. '/public_html';
    if (is_dir($dir)) {
        exec('cp -R ' .$source. '/* ' .$dir);
        // and somehow exclude overwriting any files / directories matching what's in the $exclude array
    }
}

So, my question is, how would a bash script with similar functionality be written?

3
  • do u want copy from /home/user1/public_html to another directory or 2 another directory ?
    – Soheil
    Mar 24, 2015 at 17:17
  • Copy the files from /home/user1/public_html (source) to /home/user2/public_html, /home/user3/public_html and /home/user4/public_html (the destinations), for example.
    – MattD
    Mar 24, 2015 at 17:58
  • you use for loop` for ((i=1;i<5;i++)); do cp -R /home/user$i/public_html/* /tmp/user$i/* ; done;`
    – Soheil
    Mar 24, 2015 at 18:06

1 Answer 1

0

Here's how I ended up doing it:

#!/bin/bash
while IFS= read -r line || [[ $line ]]; do
    if [[ -d "$line" ]]; then
        rsync -rv --exclude-from "exclude.txt" /home/source/public_html/ "$line"
    else
        echo "Directory $line does not exist!"
    fi
done < "accounts.txt"

This reads from a file called "accounts.txt" that has all the destination account directories in it, one per line. Ex:

/home/user1/public_html
/home/myblog/public_html

It loops through each one, and if the directory exists, it copies the files from /home/source/public_html to the destination. It also reads from a file called "exclude.txt" that includes, one per line, any files or directories to exclude. Ex:

.git
/uploads/custom
/config/conf.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.