读取循环的Shell脚本只执行一次 [英] Shell script while read loop executes only once
问题描述
我正在编写一个shell脚本,通过 Handbrake 将相机的.mov文件批量处理掉。节省高清空间。该脚本使用find搜索目录,然后在找到的每个.mov文件上运行Handbrake,并使用touch将结果文件的创建日期与源文件的日期进行匹配。
for $ in $(find $ *-iname'* .mov');做
〜/ Unix / HandbrakeCLI - 输入$ i - 输出$ i.mp4 --preset =Normal
touch -r$ i$ i.mp4
完成
这个工作,但如果输入文件的文件名中有空格,则失败。所以我尝试了 while 循环:
find$ *-iname'* .mov '|同时读我;做
〜/ Unix / HandbrakeCLI - 输入$ i - 输出$ i.mp4 --preset =Normal
touch -r$ i$ i.mp4
完成
这个循环的问题在于它适用于目录中的第一个文件,然后退出循环。请注意,如果我在while循环的主体中替换echo $ i,它将打印目录中的所有.mov文件,因此循环结构正确。
我相信在我的问题上有部分答案, -once>这个stackoverflow线程。但解决方案是特定于SSH,并不能解决一般问题。似乎有一些与标准程序正在使用的子进程有关,但我不完全明白这是如何工作的。
任何建议吗?
我在OSX 10.6上解决方案
有一种可能是使用安全查找:
while IFS = read -r -d''-u 9
do
〜/ Unix / HandbrakeCLI --input$ REPLY--output $ REPLY.mp4 --preset =Normal
touch -r$ REPLY$ REPLY.mp4
done 9< <(找到$ @-type f -print0)
这应该是POSIX兼容的,但是只有当 HandbrakeCLI
和 touch
从标准输入和中读取时,<文件名>才包含换行符:
find$ @-type f -print0 | while IFS = read -r
do
〜/ Unix / HandbrakeCLI --input$ REPLY--output$ REPLY.mp4 --preset =Normal
touch -r $ REPLY$ REPLY.mp4
done
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
One possibility is to use the safe find:
while IFS= read -r -d '' -u 9
do
~/Unix/HandbrakeCLI --input "$REPLY" --output "$REPLY".mp4 --preset="Normal"
touch -r "$REPLY" "$REPLY".mp4
done 9< <( find "$@" -type f -print0 )
This should be POSIX compatible, but only works if neither HandbrakeCLI
nor touch
read from standard input and no file names contain newlines:
find "$@" -type f -print0 | while IFS= read -r
do
~/Unix/HandbrakeCLI --input "$REPLY" --output "$REPLY".mp4 --preset="Normal"
touch -r "$REPLY" "$REPLY".mp4
done
这篇关于读取循环的Shell脚本只执行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!