0

I am trying to write a script using a for loop to copy files to a directory that will also echo the copy command to the terminal. I have successfully gotten the script to copy files, however, am having issues making it echo each copy command to the terminal. For example, if it copies files a, b, and c, to directory 2, I want it to say each time it copies a file path/file copied to /path/path/directory.

This is what I have so far:

for i in /Users/ashleyschumann/Pictures                          
do
    cp -r ./Pictures ./BACKUP_FILES2

    #echo "filename copied to BACKUP_FILES2"
    #echo "$fn copied to $ashleyschumann/BACKUP_FILES2"
done

The two commented lines I have both tried and neither got the desired result. Any help would be appreciated.

2
  • 2
    Are you looking for something different from cp -v? – muru Feb 20 '20 at 7:00
  • ... or rsync -v – Kusalananda Feb 20 '20 at 7:34
2

Your for loop only results in one item and this is then not used in your cp command. It could look like this:

BACKUP_DIR="/Users/ashleyschumann/BACKUP_FILES2/"
for item in /Users/ashleyschumann/Pictures/*
do
    cp -r $item ./BACKUP_FILES2
    echo "$item copied to $BACKUP_DIR"
done

But as muru already stated cp -v will do this.

1
  • Thank you! I ended up using this in combination with set -x at the top of my script and it worked. – Ash Feb 21 '20 at 3:58
0

The easiest would be to enable verbose mode on the copy command

cp -av Pictures BACKUP_FILES2/

Or

rsync -av Pictures BACKUP_FILES2/

If you want to customise the message you need to iterate across the files. Since you haven't told us whether or not Pictures contains directories of files, I'm going to provide some alternative solutions.

First, a single level directory of files

#!/bin/bash
# Backup files from a single level directory
target=BACKUP_FILES2/Pictures

# ensure target exists
mkdir -p "$target"

# here we go
for pic in Pictures/*
do
    if [[ -f "$pic" ]]
    then
        # it's a file
        cp -p "$pic" "$target/" &&
            echo "Copied $pic" >&2
    fi
done

Next a couple of options for a directory tree of files.

#!/bin/bash
# Backup a tree of files using cp and a customised message
target=BACKUP_FILES2

find Pictures -exec bash -c '
    for i in "$@"
    do
        if [[ -d "$i" ]]
        then
            mkdir -p "/tmp/target/$i" && echo "Created directory $i" >&2
        else
            cp -p "$i" /tmp/target/"$i" && echo "Copied $i" >&2
        fi
    done
' _ {} +

Or

#!/bin/bash
# Backup a tree of files using rsync and a customised message
target=BACKUP_FILES2

find Pictures -type f -exec bash -c '
    for i in "$@"
    do
        rsync -aqR --no-r "$i" "$target" && echo "Copied $i" >&2
    done
' _ {} +

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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