1

I am trying to write a bash script to copy files with cp or, preferably, rsync and then move the source files to the trash. I do not want to use mv because in case of an error, I want to be able to recover the source files.

This script works. It hard codes the destination folder.

for i in "$@"; do
    cp -a -R "$i" '/home/userxyz/Downloads/folder1'
    gio trash "$i"
done

However, this script that uses a variable for the destination folder does not work.

read -p "Enter destination folder: " destination

for i in "$@"; do
    cp -a -R "$i" "$destination"
    gio trash "$i"
done

Error when I enter '/home/userxyz/Downloads/folder1' as destination:

cp: cannot create regular file "'/home/userxyz/Downloads/folder1'": No such file or directory

Similarly, this works:

for i in "$@"; do
    rsync "$i" '/home/userxyz/Downloads/folder1'
    gio trash "$i"
done

But this does not work:

read -p "Enter destination folder: " destination

for i in "$@"; do
    rsync "$i" "$destination"
    gio trash "$i"
done

Error:

rsync: change_dir#3 "/home/userxyz//'/home/userxyz/Downloads" failed: No such file or directory (2)
rsync error: errors selecting input/output files, dirs (code 3) at main.c(720) [Receiver=3.1.3]

I have confirmed that '/home/userxyz/Downloads/folder1' exists. What am I doing wrong?

4
  • You seem to be including quotes when entering the destination name. If so, leave them out. If not, add set -x to the script to see what's going on there. Commented Apr 17, 2021 at 3:58
  • cp -a includes -R, so you don't need that option (and rsync also has an -a / --archive option). You also don't need that loop, replace "$i" with "$@". Commented Apr 17, 2021 at 4:15
  • @berndbausch Thank you very much! Leaving out the quotes solved my problem. Commented Apr 17, 2021 at 4:58
  • @Freddy Thank you for your suggestion. I removed the loop and changed the rsync/cp options per your recommendation. Commented Apr 17, 2021 at 4:59

1 Answer 1

0

Thank you for your helpful suggestions, @berndbausch and @Freddy! It turns out that the single quotes in the destination name were the problem. I modified the script to remove the single quotes and also remove the unnecessary loop. It now works with both rsync and cp.

read -p "Enter destination folder: " destination

dest="${destination%\'}" #remove the suffix ' (escaped with a backslash to prevent shell interpretation)
dest="${dest#\'}" #remove prefix ' (escaped with a backslash to prevent shell interpretation)

rsync -a -W "$@" $dest #or cp -a "$@" $dest
gio trash "$@"
1
  • 1
    Better still, don't provide the single quotes in the first place. No other utility expects them Commented Apr 17, 2021 at 8:35

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.