Search code examples
bashscripting

Could someone help me with my bash script that copies contents of a directory and pastes it to multiple servers?


I have a script that copies the contents of a directory. This directory contains drivers organized by computer model name. I would like to be able to update my main node (drop edited cab files) and have its entire content sent to multiple servers on the network. I have this working now, however its copying over everything in the main directory. I only want updated directories. Is there a way I can do this?

#!/bin/bash
#source directory
source_directory="/images/drivers"

#remote username
remote_user="username"

#array of remote server IPs
remote_servers=("10.xx.xx.xxx" "10.xx.xx.xxx")

#Destination directory on remote servers
destination_directory="/images/drivers"

#specify the user and group ownership for the copied directories
ownership="name:name"

#Loop through each remote server and copy the contents
for server in "${remote_servers[@]}"; do
        rsync -avs --ignore-existing --chown="$ownership" "$source_directory/" "$remote_user@$server:$destination_directory/"
done

Solution

  • You're missing " for ownership variable. And the --ignore-existing flag is currently set, which means files that already exist on the receiver side will not be overwritten.

    Use --checksum or -c flag with rsync. Use --delete flag to delete extraneous files from destination directories. Use this if you want to keep the destination strictly in sync with the source directory, meaning if you delete a file in the source, it will also be deleted in the destination.

    #!/bin/bash
    # Source directory
    source_directory="/images/drivers"
    
    # Remote username
    remote_user="username"
    
    # Array of remote server IPs
    remote_servers=("10.xx.xx.xxx" "10.xx.xx.xxx")
    
    # Destination directory on remote servers
    destination_directory="/images/drivers"
    
    # Specify the user and group ownership for the copied directories
    ownership="name:name"
    
    # Loop through each remote server and copy the updated contents
    for server in "${remote_servers[@]}"; do
        rsync -avs --checksum --chown="$ownership" "$source_directory/" "$remote_user@$server:$destination_directory/"
    done
    

    Keep in mind that using the --checksum flag can be CPU intensive, especially for large directories. So, test thoroughly before deploying.