我正在尝试编写一个 bash 脚本来使用 cp 或最好使用 rsync 复制文件,然后将源文件移至垃圾箱。我不想使用 mv 因为如果出现错误,我希望能够恢复源文件。
这个脚本有效。它对目标文件夹进行硬编码。
for i in "$@"; do
cp -a -R "$i" '/home/userxyz/Downloads/folder1'
gio trash "$i"
done
但是,此使用目标文件夹变量的脚本不起作用。
read -p "Enter destination folder: " destination
for i in "$@"; do
cp -a -R "$i" "$destination"
gio trash "$i"
done
当我输入“/home/userxyz/Downloads/folder1”作为目标时出错:
cp: cannot create regular file "'/home/userxyz/Downloads/folder1'": No such file or directory
同样,这也有效:
for i in "$@"; do
rsync "$i" '/home/userxyz/Downloads/folder1'
gio trash "$i"
done
但这不起作用:
read -p "Enter destination folder: " destination
for i in "$@"; do
rsync "$i" "$destination"
gio trash "$i"
done
错误:
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]
我已确认“/home/userxyz/Downloads/folder1”存在。我究竟做错了什么?
答案1
感谢您的有用建议,@berndbausch 和 @Freddy!事实证明,目标名称中的单引号是问题所在。我修改了脚本以删除单引号并删除不必要的循环。现在它可以与 rsync 和 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 "$@"