Bash脚本用于在目录之间复制文件

3
我正在编写以下脚本,将*.nzb文件复制到一个文件夹中以排队下载。
我编写了以下脚本。
#!/bin/bash

#This script copies NZB files from Downloads folder to HellaNZB queue folder.

${DOWN}="/home/user/Downloads/"
${QUEUE}="/home/user/.hellanzb/nzb/daemon.queue/"


for a in $(find ${DOWN}  -name  *.nzb)
do
cp ${a} ${QUEUE}
rm *.nzb
done

它给我以下错误提示:

HellaNZB.sh: line 5: =/home/user/Downloads/: No such file or directory
HellaNZB.sh: line 6: =/home/user/.hellanzb/nzb/daemon.queue/: No such file or directory

事实是这些目录存在,我有权访问它们。

任何帮助都将不胜感激。

谢谢你的帮助。


1
你可以使用 find 命令中的 -exec 参数来简化它:find $DOWN -name *.nzb -exec mv {} $QUEUE \; - SiggyF
3个回答

8

赋值语句左侧的变量名应该是裸露的。

foo="something"
echo "$foo"

以下是您脚本的一些改进:

在这里有一些关于您的脚本的更多改进:

#!/bin/bash

#This script copies NZB files from Downloads folder to HellaNZB queue folder.

down="/home/myusuf3/Downloads/"
queue="/home/myusuf3/.hellanzb/nzb/daemon.queue/"

find "${down}" -name "*.nzb" | while read -r file
do
    mv "${file}" "${queue}"
done

使用while代替for,并引用包含文件名的变量可以防止将空格视为多个文件名进行解释。删除rm可避免重复产生错误并且只复制第一个文件。对于-name的文件通配符需要加上引号。习惯性地使用小写变量名称可以减少与shell变量名称冲突的机会。
顺便说一下,如果您的所有文件都在一个目录中(而不是在多个子目录中),则整个脚本可以简化为以下内容:
mv /home/myusuf3/Downloads/*.nzb /home/myusuf3/.hellanzb/nzb/daemon.queue/

如果您有多个子目录中的文件:

find /home/myusuf3/Downloads/ -name "*.nzb" -exec mv {} /home/myusuf3/.hellanzb/nzb/daemon.queue/ +

正如您所看到的,不需要循环。

哈哈,我真是太蠢了,谢谢!我一直都想不出问题出在哪里。 - Mahdi Yusuf

1
for a in $(find ${DOWN}  -name  *.nzb)
   # escape the * or it will be expanded in the current directory
   # let's just hope no file has blanks in its name
do
  cp ${a} ${QUEUE}  # ok, although I'd normally add a -p
  rm *.nzb          # again, this is expanded in the current directory
                    # when you fix that, it will remove ${a}s before they are copied

done

为什么不直接使用rm $(a}呢?

为什么要使用cp和rm的组合,而不是mv呢?

你是否意识到所有文件最终都会在同一个目录中,来自不同目录的同名文件将互相覆盖?

如果cp失败了怎么办?你会失去你的文件。


1

正确的语法是:

DOWN="/home/myusuf3/Downloads/"
QUEUE="/home/myusuf3/.hellanzb/nzb/daemon.queue/"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接