DEV Community

Frank Etoundi
Frank Etoundi

Posted on

Bash: Compare files and copy them to another folder if they don't exist

You can compare files in bash and copy them to another folder if they don't exist in the destination folder using the following script:

#!/bin/bash

# Set the source and destination directories
source_dir=<path_to_source_folder>
destination_dir=<path_to_destination_folder>

# Get a list of files in the source directory
files=$(ls "$source_dir")

# Loop through the list of files
for file in $files
do
  # Check if the file exists in the destination directory
  if [ ! -f "$destination_dir/$file" ]; then
    # If the file does not exist, copy it to the destination directory
    cp "$source_dir/$file" "$destination_dir/$file"
    echo "Copied $file to $destination_dir"
  else
    echo "$file already exists in $destination_dir"
  fi
done
Enter fullscreen mode Exit fullscreen mode

This script sets the source and destination directories, then gets a list of files in the source directory using the ls command. It then loops through the list of files, checking if each file exists in the destination directory using the if statement and the -f option of the [ command. If the file does not exist in the destination directory, it is copied using the cp command. A message is printed indicating whether the file was copied or if it already exists in the destination folder.

Top comments (1)

Collapse
 
howtouselinux profile image
howtouselinux

You can also check rsync command for this purpose.