How to configure the find command to run in a Linux shell script?

I am trying to run the following find command in a Linux shell script. When I run the command in the terminal, it successfully finds all the files with the extension .mp4 from the specified folder, and copies them to a temp folder.

find /datadrive/reports/ -name \*.mp4 -exec cp {} 
/datadrive/reports/video_tmp/ \;

However, when I run it in my file_mover.sh

Code:

SHELL=/bin/bash
PATH=~/find /datadrive/reports/ -name '\*.mp4' -exec cp {} 
/datadrive/reports/video_tmp/ \;
done
MAILTO=root

Output:

./file_mover.sh: line 2: /datadrive/reports/: Is a directory.

I think I'm missing syntax somewhere in the script, and any help would be appreciated.

linuxbashshellfind

Answers

answered 4 months ago Charles Duffy #1

The following is a perfectly valid script:

#!/bin/sh
find /datadrive/reports/ -name '*.mp4' -exec cp -t /datadrive/reports/video_tmp/ '{}' +

Note the changes:

  • We aren't trying to assign to PATH. This is a variable with special meaning (it determines where programs are found), so reassigning it generally messes things up.
  • We aren't using a backslash inside single quotes. -name \*.mp4 is legal as a match for all files ending in .mp4. -name '*.mp4' is legal for the same purpose. You can't combine the two and have it still mean what you want.
  • By using cp -t dest source1 source2 ..., we're allowing find to only run cp the shortest number of times needed to put the destination filenames on the command line.

There's also no point to assigning SHELL and MAILTO; they're meaningful in a crontab (and some other specific/narrow circumstances), but not in a general-purpose script.

comments powered by Disqus