【问题标题】:bash scripting, handling spaces in filesnames in a for loop strange behaviourbash脚本,在for循环中处理文件名中的空格奇怪的行为
【发布时间】:2016-03-17 14:51:09
【问题描述】:

帮助。我尝试过的一切都失败了。我正在尝试修复我的视频收藏,其中很多在名称/等中有空格我想对它们进行转码,我已经编写了下面的脚本,但它失败了。我用于测试的两个文件名是“13 Eerie (2013).avi”和“Ace.Ventura.When.Nature.Calls.1995.720p.WEB-DL.x264-mSD.mkv”

我已经尝试了几件事,从在 find 上使用 print0 到破坏 IFS。任何援助将不胜感激。由于某些原因,当前版本将 e 字符上的所有内容分开


convert.sh

#!/bin/sh

OUTDIR="./done/"
LOGDIR="./logs/"
BACKUPDIR="./backup/"

# deal with spaces
SAVEIFS=$IFS
IFS=$(echo -en "\n")

# pull all files except MP4 or scripts in the CURRENT DIR only
for FULLFILENAME in `find . -maxdepth 1 -type f -not -iname "*.sh" -not -iname "*.mp4" -print`
do
    # extract the file extension
    filename=$(basename "$FULLFILENAME")
    ext="${filename##*.}"
    filename="${filename%.*}"

    # use handbrake to convert to x264
    HandBrakeCLI -i "$FULLFILENAME" -o "$OUTDIR$filename.mp4" -e x264 -q 22 -r 29.97 -B 64 -O 2>$LOGDIR$filename.log

    # move the original file to a backup
    mv "$FULLFILENAME" $BACKUPDIR
done

#restore the field separator
IFS=$SAVEIFS

【问题讨论】:

    标签: linux bash shell handbrake


    【解决方案1】:
    • 不要使用find 的命令替换
    • 不要使用 for 循环
    • 使用进程替换从find 获取输出
    • 使用-print0 选项并使用while 循环读取
    • 最好避免使用大写的变量名
    • 使用bashshebang

    代码:

    #!/bin/bash
    
    outdir="./done/"
    logdir="./logs/"
    backupdir="./backup/"
    
    
    # pull all files except MP4 or scripts in the CURRENT DIR only
    while IFS= read -r -d '' fullfilename
    do
        # extract the file extension
        filename="$(basename "$fullfilename")"
        ext="${filename##*.}"
        filename="${filename%.*}"
    
        # use handbrake to convert to x264
        HandBrakeCLI -i "$fullfilename" -o "$outdir$filename.mp4" -e x264 -q 22 -r 29.97 -B 64 -O 2>"$logdir$filename.log"
    
        # move the original file to a backup
        mv "$fullfilename" "$backupdir"
    done < <(find . -maxdepth 1 -type f -not -iname "*.sh" -not -iname "*.mp4" -print0)
    

    【讨论】:

    • Don't read lines with forBash FAQ 001 是列出建议的相关读数。
    • 删除了之前的响应,我对进程替换做了更多阅读,现在我得到了语法,但它不适用于重定向意外错误
    • @JamesWilson:在顶部使用#!/bin/bash,就像在编辑的答案中一样。
    • @anubhava - 你是我的救星先生。我的 sh 链接到 bash 但手动指定它修复了它,这很奇怪。 +1啤酒
    • 为了增加混乱,我注释掉了 HandbrakeCLI 命令并添加了一个 echo "Converting $fullfilename" ,它的行为就像两者一样,但是当手刹运行时它似乎被踢了。这会避开它的手刹,而不是脚本。我接受这是一个解决方案。
    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    相关资源
    最近更新 更多