Created
June 19, 2025 02:21
-
-
Save Ansen/bf7a43d6cb88ecadc5090ccbc1c86d11 to your computer and use it in GitHub Desktop.
trim_video.sh Video Trimming Script (FFmpeg-based)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# 显示帮助信息 | |
show_help() { | |
cat << EOF | |
用法: $0 [选项] | |
选项: | |
-i, --input-file <文件> 输入视频文件 | |
-o, --output-file <文件> 输出视频文件 (默认: 输入文件名加 '_trim') | |
-ss, --start-time-offset <时间> 开始时间偏移 (格式: HH:MM:SS) | |
-to, --time-stop <时间> 停止时间 (格式: HH:MM:SS) | |
-t, --duration <时间> 剪辑持续时间 (单位: 秒),如果提供此选项,则忽略 -to | |
-h, --help 显示帮助信息 | |
示例: | |
$0 -i input.mp4 -o output.mp4 -ss 01:43 -to 01:49 | |
$0 -i input.mp4 -o output.mp4 -ss 01:43 -t 60 | |
EOF | |
exit 0 | |
} | |
# 打印绿色信息(兼容性好一点) | |
green_echo() { | |
if [ -t 1 ]; then | |
echo -e "\033[32m$1\033[0m" | |
else | |
echo "$1" | |
fi | |
} | |
# 解析参数 | |
parse_args() { | |
while [ $# -gt 0 ]; do | |
case "$1" in | |
-i|--input-file) | |
input_file="$2"; shift 2 ;; | |
-o|--output-file) | |
output_file="$2"; shift 2 ;; | |
-ss|--start-time-offset) | |
start_time="$2"; shift 2 ;; | |
-to|--time-stop) | |
end_time="$2"; shift 2 ;; | |
-t|--duration) | |
duration="$2"; shift 2 ;; | |
-h|--help) | |
show_help ;; | |
*) | |
echo "未知选项: $1" | |
show_help ;; | |
esac | |
done | |
} | |
# 构造并运行 ffmpeg 命令 | |
run_ffmpeg_trim() { | |
# 输入文件检查 | |
if [ -z "$input_file" ]; then | |
echo "错误: 输入文件未提供" | |
show_help | |
fi | |
if [ ! -f "$input_file" ]; then | |
echo "错误: 输入文件不存在: $input_file" | |
exit 1 | |
fi | |
# 默认输出文件名 | |
if [ -z "$output_file" ]; then | |
base_name="$(basename "$input_file")" | |
output_file="${base_name%.*}_trim.mp4" | |
fi | |
# 构建 ffmpeg 参数 | |
args=( -i "$input_file" -ss "$start_time" ) | |
if [ -n "$duration" ]; then | |
args+=( -t "$duration" ) | |
elif [ -n "$end_time" ]; then | |
args+=( -to "$end_time" ) | |
fi | |
args+=( -c copy "$output_file" ) | |
# 执行命令 | |
ffmpeg "${args[@]}" | |
if [ $? -ne 0 ]; then | |
echo "错误: ffmpeg 执行失败" | |
exit 1 | |
fi | |
# 输出完成信息 | |
green_echo "视频剪辑完成: 输出文件 '$output_file'" | |
if [ -n "$duration" ]; then | |
green_echo "剪辑持续时间: ${duration} 秒" | |
else | |
green_echo "剪辑从 $start_time 到 $end_time" | |
fi | |
} | |
# 设置默认值 | |
input_file="" | |
output_file="" | |
start_time="00:00:00" | |
end_time="" | |
duration="" | |
# 脚本入口 | |
main() { | |
parse_args "$@" | |
run_ffmpeg_trim | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment