奇怪的问题读取带空格的文件(Shell脚本)

时间:2018-11-25 16:20:40

标签: bash shell

这是我的代码:

#!/bin/bash

# https://askubuntu.com/a/343753
# http://wiki.bash-hackers.org/commands/builtin/read
# (use null character to separate a list of filenames)
# (sets IFS in the environment for just the read command)
log=./log.txt
OLDIFS=$IFS
find $1 -type f -name '*.MTS' -print0 |
while IFS= read -r -d '' input; do
    # set IFS to null string to preserve whitespace when $input is used
    IFS=''
    echo ""
    echo "input='${input}'"
    echo "`sha1sum "${input}"`"
    output="${input%.MTS}.mp4" # change extension to MTS
    ffmpeg -i "$input" -n -c:v copy -c:a aac -strict experimental -b:a 128k "$output" >> "$log" 2>&1
    if [ $? != 0 ]; then
        echo "FAILED: "$input" -> "$output""
    else
        touch -r "$input" "$output"  # copy original file's metadata
        echo "SUCCESS: "$input" -> "$output"" # indicate success
    fi

done
IFS=$OLFDIFS
echo "------"

请注意,无论我是否注释掉ffmpeg行,输出都会如何变化: enter image description here

我的问题是,当使用ffmpeg命令时,为什么读入的第二个文件名会弄乱?

2 个答案:

答案 0 :(得分:0)

双引号不能引用双引号。像这样使用反斜杠:\"。例子:

echo "foo "bar     baz" bang"

输出,没有引号,没有空格:

foo bar baz bang

现在使用反斜杠:

echo "foo \"bar     baz\" bang"

输出,显示空格。

foo "bar     baz" bang

实际代码有两行是这样的:

echo "FAILED: "$input" -> "$output""

因此将其更改为:

echo "FAILED: \"$input\" -> \"$output\""

答案 1 :(得分:0)

戈登指出的答案是,我必须

在我的ffmpeg命令的最后,原因解释为here

我确实有一些用双引号引起来的问题,但这不是造成此问题的原因。谢谢大家!