bash 中 ffmpeg 文件名中的空格

Spaces in filename for ffmpeg in bash

我尝试使用 ffmpeg 为 VHS 备份编写一个简单的转码脚本。但是我无法处理文件名中的空格。

我在脚本中一起构建我的 ffmpeg 命令并回显它,当我复制粘贴回显命令时它可以工作,但不是直接来自脚本。

有人知道我的脚本有什么问题吗?

脚本:

#!/bin/bash
# VHStoMP4Backup Script

INPUT=
OUTPUT="/Volumes/Data/oliver/Video/Encodiert/"

command="ffmpeg \
    -i \"$INPUT\" \
    -vcodec copy \
    -acodec copy \
    \"$OUTPUT\""


if [ ! -z "" ] && [ ! -z "" ] ;
then
    echo ${command}$'\n'
    ${command}
else
    echo "missing parameters"
    echo "Usage: script INPUT_FILENAME OUTPUT_FILENAME"
fi

exit

脚本调用:

./VHStoMP4Backup.sh /Volumes/Data/oliver/Video/RAW\ Aufnahmen/Ewelina\ -\ Kasette\ 1.dv ewe.mp4

命令行输出

olivers-mac-pro:Desktop oliver$ ./VHStoMP4Backup.sh /Volumes/Data/oliver/Video/RAW\ Aufnahmen/Ewelina\ -\ Kasette\ 1.dv ewe.mp4
    ffmpeg -i "/Volumes/Data/oliver/Video/RAW Aufnahmen/Ewelina - Kasette 1.dv" -vcodec copy -acodec copy "/Volumes/Data/oliver/Video/Encodiert/ewe.mp4"

    ffmpeg version git-2016-04-16-60517c3 Copyright (c) 2000-2016 the FFmpeg developers
      built with Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
      configuration: --prefix=/usr/local/Cellar/ffmpeg/HEAD --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-opencl --enable-libx264 --enable-libmp3lame --enable-libxvid --enable-libfreetype --enable-libvorbis --enable-libvpx --enable-librtmp --enable-libfaac --enable-libass --enable-libssh --enable-libspeex --enable-libfdk-aac --enable-openssl --enable-libopus --enable-libvidstab --enable-libx265 --enable-nonfree --enable-vda
      libavutil      55. 22.100 / 55. 22.100
      libavcodec     57. 34.102 / 57. 34.102
      libavformat    57. 34.101 / 57. 34.101
      libavdevice    57.  0.101 / 57.  0.101
      libavfilter     6. 42.100 /  6. 42.100
      libavresample   3.  0.  0 /  3.  0.  0
      libswscale      4.  1.100 /  4.  1.100
      libswresample   2.  0.101 /  2.  0.101
      libpostproc    54.  0.100 / 54.  0.100
    "/Volumes/Data/oliver/Video/RAW: No such file or directory

Never store a command and its arguments in a regular variable,期望通过扩展变量来执行命令。

使用数组存储参数,然后在调用实际命令时扩展数组。

if [ $# -lt 3 ]; then
    echo "missing parameters"
    echo "Usage: script INPUT_FILENAME OUTPUT_FILENAME"
else
    INPUT=
    OUTPUT="/Volumes/Data/oliver/Video/Encodiert/"

    args=( -i "$INPUT" -vcodec -acodec "$OUTPUT" )
    ffmpeg "${args[@]}"
fi

您需要做更多的工作才能正确记录命令,但这是为安全、正确的代码付出的小代价。

printf 'ffmpeg'
printf ' %q' "${args[@]}"
printf '\n'

(记录的命令看起来并不完全像您期望的那样,但它可以用作 运行 相同命令的有效命令行。特别是, %q 说明符倾向于使用反斜杠单独转义字符,而不是将较长的字符串放在引号中。)