Pass Bash Variables to FFmpeg
This article provides a quick overview and practical guide on how to safely and effectively pass Linux Bash variables into an FFmpeg command. You will learn the correct syntax for standard variable substitution, how to handle complex arguments containing spaces, and how to safely environment-export variables for advanced filtering scripts.
Standard Variable Substitution
The most straightforward way to pass a Bash variable into an FFmpeg
command is by using double quotes (""). In Bash, variables
inside double quotes are expanded by the shell before the command is
executed, whereas single quotes ('') treat the variable
name as literal text.
Here is the basic syntax for passing an input file, an output file, and a video bitrate variable:
#!/bin/bash
INPUT_FILE="input.mp4"
OUTPUT_FILE="output.mkv"
BITRATE="5M"
ffmpeg -i "$INPUT_FILE" -b:v "$BITRATE" "$OUTPUT_FILE"Handling Spaces and Special Characters
Always wrap your Bash variables in double quotes when passing them to FFmpeg. If your file names or paths contain spaces, omitting the quotes will cause Bash to split the variable into multiple arguments, leading to an FFmpeg “No such file or directory” error.
- Correct:
ffmpeg -i "$INPUT_FILE" "$OUTPUT_FILE" - Incorrect:
ffmpeg -i $INPUT_FILE $OUTPUT_FILE
Passing Variables Inside Complex Filters
When using FFmpeg’s complex filtergraphs
(-filter_complex or -vf), you often need to
use single quotes to wrap the filter chain. Because Bash does not expand
variables inside single quotes, you must step out of the single quotes
to inject your variable.
Here is the syntax to pass a variable into a drawtext
filter:
#!/bin/bash
WATERMARK_TEXT="Property of ACME"
ffmpeg -i input.mp4 -vf "drawtext=text=''"$WATERMARK_TEXT"'':x=10:y=10" output.mp4Alternatively, you can use double quotes for the entire filter string, but you must escape the internal quotes required by FFmpeg:
ffmpeg -i input.mp4 -vf "drawtext=text=\"$WATERMARK_TEXT\":x=10:y=10" output.mp4