读取循环时的 Shell 脚本仅执行一次 [英] Shell script while read loop executes only once

查看:65
本文介绍了读取循环时的 Shell 脚本仅执行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 shell 脚本来通过 Handbrake 从我的相机中批量处理 .mov 文件以节省高清空间.该脚本使用find"搜索目录,然后对找到的每个 .mov 文件运行 Handbrake,使用touch"将结果文件的创建日期与源文件的日期匹配.

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'.

我最初是用 for 循环做到的:

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

这行得通,但如果输入文件的文件名中有空格,则失败.所以我尝试了一个 while 循环:

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

这个循环的问题在于它对目录中的第一个文件起作用,然后退出循环.请注意,如果我在 while 循环体中替换了echo $i",它会打印目录中的所有 .mov 文件,因此循环结构正确.

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.

我相信我在 这个stackoverflow 线程.但该解决方案特定于 ssh,并不能解决一般问题.似乎与子进程使用的标准输入有关,但我并不完全理解这是如何工作的.

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.

有什么建议吗?

我使用的是 OSX 10.6

I'm on OSX 10.6

推荐答案

摘自这个答案:我现在什么都不回响进入 HandbrakeCLI 以确保它不使用与我的脚本相同的标准输入:

Taken from this answer: I now echo nothing into HandbrakeCLI to ensure it's not using the same stdin as my script:

find . -name "*.mkv" | while read FILE
do
    echo "" | handbrake-touch "$FILE"

    if [ $? != 0 ]
    then
        echo "$FILE had problems" >> errors.log  
    fi
done

...它按预期/预期工作.

...and it works as intended/expected.

这篇关于读取循环时的 Shell 脚本仅执行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆