linux - 为什么 shell 脚本中的 'read' 命令缺少初始字符?

标签 linux bash shell ubuntu ffmpeg

<分区>

我有以下 shell 脚本,除第一行外,它的每一行都缺少一些初始字符(据我观察,它缺少初始的几个字符)。

只有当我使用 ffmpeg 命令时才会发生这种情况。否则,没关系。但是此命令执行此脚本中的实际任务。

为什么会这样,解决方法是什么?

#!/bin/bash

while read line; do
    printf "%s\n" "$line" 
    ifile=$line
    printf "%s\n" "$ifile" 
    ofile=abc_$line
    printf "%s\n" "$ofile" 

    ############### Problem is the following command: ##########
    ffmpeg -y -i $ifile -c:v libx264rgb -b:v 512k -bf 0 -pix_fmt rgb24  -r 25 -strict -2 $ofile
    ##########rest is fine##########

    echo $ifile
done < file_list

最佳答案

这在这篇文章中得到了很好的解释 I'm reading a file line by line and running ssh or ffmpeg, only the first line gets processed! .逐行读取文件时,如果循环内的命令也读取 stdin,则可能会耗尽输入文件。在你的情况下 ffmpeg也从标准输入读取。

最常见的症状是 while read 循环只运行一次,即使输入包含很多行。这是因为其余的行被有问题的命令吞没了。该问题最常见的解决方法是关闭 ffmpeg 的标准输入。通过做< /dev/null

ffmpeg -y -i "$ifile" -c:v libx264rgb -b:v 512k -bf 0 -pix_fmt rgb24  -r 25 -strict -2 "$ofile" < /dev/null

或者使用标准输入以外的其他文件描述符

 while read -r line <&3; do
     ifile="$line"
     ofile="abc_${line}"
     ffmpeg -y -i "$ifile" -c:v libx264rgb -b:v 512k -bf 0 -pix_fmt rgb24  -r 25 -strict -2 "$ofile"
 done 3<file

或者您的问题完全可能是输入文件具有从 DOS 环境中继承的 DOS 样式行结尾的情况。您可以通过运行 file 来检查这一点输入文件 ( file file_list ) 上的命令可以显示 CRLF line terminators .在这种情况下,将输入文件清理为 dos2unix file_list并重新运行您的脚本。

关于linux - 为什么 shell 脚本中的 'read' 命令缺少初始字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55682533/

相关文章:

c - Bash 返回简单 C 程序的权限被拒绝

linux - 如何在一行中的 bash 中运行多个后台命令?

shell 脚本: Read line in file

linux - bzip 命令不适用于 "tee -a"

c++ - 使用 distcc 在 Ubuntu 上的 i686 系统上交叉编译 x86_64

ruby - 成功使用后和几天后的 RVM 'not found'

使用 Shell 脚本更改 C 程序中的某些内容

显示系统物理 IP 的 linux 命令

python - 如何在安装前检查 SD 卡大小并且不需要 root

Bash通过多字符定界符将多行字符串拆分为数组