You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shell脚本无法识别文件名中的空格与连字符问题求助

解决Shell脚本无法识别含空格/连字符文件名的问题

你的脚本核心问题是变量拼接时的引号使用错误,导致带空格的文件名被Shell拆分成多个参数,ffmpeg无法定位到目标文件;同时不管转换是否成功都会直接删除源文件夹,风险极高。以下是修复后的脚本及问题说明:

修复后的脚本

echo "Warning! Please ensure before running this script 
    that the files you'd like to convert are in the following format: 
    'series_name - SXXEYY' and mind that by running this script 
    you're aware that the uncompressed files are going to be 
    automatically deleted. If you change your mind press 'Ctrl + C' 
    to cancel or press [ENTER] to continue:"
read
echo "Enter destination of the input folder:"
read input
echo "Enter series name(how it's written inside the folder):"
read series_name
echo "Enter season number:"
read season_no
echo "Enter number of episodes in the season:"
read ep_no
echo "Enter destination of the output folder:"
read output

# 确保输出文件夹存在,避免ffmpeg因路径不存在报错
mkdir -p "$output"

conversion_success=1
for i in $(seq -f "%02g" 1 "$ep_no"); do
    # 用一对双引号包裹完整路径,确保空格、连字符被正确识别为文件名的一部分
    input_file="$input/${series_name} - S${season_no}E${i}.mkv"
    output_file="$output/${series_name} - S${season_no}E${i}.mkv"
    
    echo "Processing file: $input_file"
    # 执行转换并检查命令返回值,失败则终止流程
    ffmpeg -hide_banner -i "$input_file" -c:v libx264 -crf 22 -c:a copy -c:s copy -map 0 "$output_file"
    if [ $? -ne 0 ]; then
        echo "Error converting $input_file!"
        conversion_success=0
        break
    fi
done

# 仅当所有文件转换成功时,才删除源文件夹
if [ "$conversion_success" -eq 1 ]; then
    echo "All conversions completed successfully. Deleting source folder..."
    rm -rf "$input"
else
    echo "Conversion failed. Source folder retained."
fi

clear
echo "Done :)"

关键修改说明

  • 引号规范:将input_file和output_file的拼接改为用一对双引号包裹完整路径,彻底解决空格、连字符导致的文件名拆分问题。
  • 错误拦截:通过$?判断ffmpeg命令是否执行成功,一旦转换失败就终止脚本,避免无效操作和后续误删。
  • 安全删除:只有所有文件都转换成功后,才删除源文件夹,杜绝转换失败时丢失原始文件的风险。
  • 路径保障:新增mkdir -p "$output"确保输出文件夹存在,避免ffmpeg因路径不存在抛出错误。

内容的提问来源于stack exchange,提问作者Nescada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 10:55:15