简体   繁体   English

Bash脚本找不到文件

[英]Bash script not finding files

I am writing a simple script to iterate over all the m4a files in a folder and encode them to mp3. 我正在编写一个简单的脚本来遍历文件夹中的所有m4a文件,并将它们编码为mp3。 I want to do the encoding of the files in different threads to increase the speed of execution and take advantage of all the cores in my PC, so I am sending the tasks to background, please advice me if this is the right approach. 我想对不同线程中的文件进行编码,以提高执行速度并利用PC中的所有内核,因此我将任务发送到后台,如果这是正确的方法,请告诉我。 Anyway, I am getting a No such file or direcory error for every single file that I want to encode, even though the file is there; 无论如何,即使我要编码的每个文件都出现这样的文件或目录错误,即使该文件在那里也是如此。 and the funny thing is that if I copy the exact same instruction to a terminal, it will be executed correctly. 有趣的是,如果我将完全相同的指令复制到终端,它将可以正确执行。 Can you please help me to find out what am I doing wrong? 您能帮我找出我在做什么错吗?

Thanks in advance. 提前致谢。

#!/bin/bash

function encode {
    echo "<<<<<<<<<<< encode >>>>>>>>>>>>>>>>"
    cd "$1"
    find . -mindepth 1 -maxdepth 1 | while read f
    do
        if [ -f "${f}" ]
        then
            if [ ${f: -4} == ".m4a" ]
            then
                if [ ! -d "converted" ]
                then
                    mkdir converted
                fi
                newPath="${f%m4a}mp3"
                echo "ffmpeg -i \""$f"\" -ac 2 -b:a 320k -y \""$newPath"\" </dev/null >/dev/null &"
                ffmpeg -i \""$f"\" -ac 2 -b:a 320k -y \""$newPath"\" </dev/null >/dev/null &
            fi
        elif [ -d "${f}" ]
        then
            echo "folder $f"
            encode "$f"
        fi
    done
}


encode "$1"

The problem you allude to is that you are adding literal quotes to the name of the file; 您提到的问题是您要在文件名中添加文字引号。 "$f" is sufficient to pass the value of $f as-is to the ffmpeg command. "$f"足以将$f的值原样传递给ffmpeg命令。 You don't need to use find to iterate over the immediate contents of a directory; 您无需使用find即可遍历目录的立即内容; just use a glob with a for loop (which also avoids the need to stop ffmpeg from reading from standard input). 只需使用带有for循环的glob(这样还可以避免停止ffmpeg从标准输入中读取内容)。

More subtlely, you also need encode to restore the original working directory before it returns, so that recursive calls don't "unexpectedly" change the working directory while iterating over the current directory. 更细微地讲,您还需要encode以在返回原始工作目录之前将其还原,以使递归调用不会在迭代当前目录时“意外”更改工作目录。 pushd (instead of cd ) and popd make this simple. pushd (而不是cd )和popd使此过程变得简单。

encode () {
  echo "<<<<<<<<<<< encode >>>>>>>>>>>>>>>>"
  pushd "$1"
  for f in *; do
    if [ -d "$f" ]; then
      encode "$f"
    elif [[ $f = *.m4a ]]; then
      mkdir -p converted
      newPath="${f%.m4a}.mp3"
      ffmpeg -i "$f" -ac 2 -b:a 320k -y "$newPath" > /dev/null &
    fi
  done
  popd
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM