Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script for copying files between directories

Tags:

bash

I am writing the following script to copy *.nzb files to a folder to queue them for Download.

I wrote the following script

#!/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

it gives me the following error saying:

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

Thing is that those directories exsist, I do have right to access them.

Any help would be nice.

Please and thank you.

like image 477
myusuf3 Avatar asked May 03 '26 17:05

myusuf3


2 Answers

Variable names on the left side of an assignment should be bare.

foo="something"
echo "$foo"

Here are some more improvements to your script:

#!/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

Using while instead of for and quoting variables that contain filenames protects against filenames that contain spaces from being interpreted as more than one filename. Removing the rm keeps it from repeatedly producing errors and failing to copy any but the first file. The file glob for -name needs to be quoted. Habitually using lowercase variable names reduces the chances of name collisions with shell variables.

If all your files are in one directory (and not in multiple subdirectories) your whole script could be reduced to the following, by the way:

mv /home/myusuf3/Downloads/*.nzb /home/myusuf3/.hellanzb/nzb/daemon.queue/

If you do have files in multiple subdirectories:

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

As you can see, there's no need for a loop.

like image 73
Dennis Williamson Avatar answered May 05 '26 10:05

Dennis Williamson


The correct syntax is:

DOWN="/home/myusuf3/Downloads/"
QUEUE="/home/myusuf3/.hellanzb/nzb/daemon.queue/"
like image 20
David Harris Avatar answered May 05 '26 09:05

David Harris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!