I am writing a shell script to batch process .mov files off my camera through Handbrake to save HD space. The script searches a directory with 'find' and then runs Handbrake on each .mov file found, matching the creation date of the resulting file to the source file's date with 'touch'.
I originally did this with a for loop:
for i in $(find "$*" -iname '*.mov') ; do
~/Unix/HandbrakeCLI --input "$i" --output "$i".mp4 --preset="Normal"
touch -r "$i" "$i".mp4
done
This worked, but failed if the input files had spaces in their file names. So I tried a while loop instead:
find "$*" -iname '*.mov' | while read i ; do
~/Unix/HandbrakeCLI --input "$i" --output "$i".mp4 --preset="Normal"
touch -r "$i" "$i".mp4
done
The problem with this loop is that it works for the first file in the directory, and then exits the loop. Note that if I substitute an "echo $i" in the body of the while loop, it prints all of the .mov files in the directory, so the loop is structured correctly.
I believe there is a partial answer to my question on this stackoverflow thread. But the solution is specific to ssh and doesn't solve the general problem. Seems to have something do do with stdin being used by a sub-process, but I don't exactly understand how this works.
Any advice?
I'm on OSX 10.6
You are probably running with a shellopt '-e' (exit on errors)
Try
I've got the same problem. I think HandbrakeCLI is consuming stdin. I don't have my actual system here, but my testing shows that's what is probably happening.
"output" is a file with the numbers 1-10, each on their own line.
consumer.sh:
Results:
Changing the outer while loop will fix the problem:
Results:
Taken from this answer: I now echo nothing into HandbrakeCLI to ensure it's not using the same stdin as my script:
...and it works as intended/expected.
This link fixed the problem for me on Ubuntu Linux 11.04 .
Preventing a child process (HandbrakeCLI) from causing the parent script to exit
Here is the code that works for me:
Consider just using
find
to invoke a shell, instead of wrappingfind
in awhile
loop.One possibility is to use the safe find:
This should be POSIX compatible, but only works if neither
HandbrakeCLI
nortouch
read from standard input and no file names contain newlines: