To create a Bash script for macOS or Linux that converts an MP4 file to a specified format using ffmpeg, you can use the following approach. This script will allow you to drag and drop a video file onto the script (or execute it with the video file as a parameter), and then ffmpeg will process the file according to the settings specified in your command.
First, ensure you have ffmpeg installed on your system. You can typically install it via a package manager (like brew on macOS or apt on Ubuntu Linux):
On macOS: brew install ffmpeg
On Ubuntu: sudo apt update && sudo apt install ffmpeg
Here is how you can write the script:
Open a text editor and create a new file.
Copy and paste the following Bash script into the file:
bash
#!/bin/bash
# Exit if any command fails
set -e
# Check if an argument is passed
if [[ $# -eq 0 ]]; then
echo "Usage: $0 <video_file>"
exit 1
fi
# Input file is the first argument
INPUT_FILE="$1"
# Extract filename without extension
BASENAME=$(basename "$INPUT_FILE" .mp4)
# Output filename construction
OUTPUT_FILE="${BASENAME}-converted.mp4"
# Run ffmpeg command
ffmpeg -i "$INPUT_FILE" -c:v libx264 -crf 23 -preset veryfast -c:a aac -b:a 128k -movflags +faststart -vf scale=-2:720,format=yuv420p "$OUTPUT_FILE"
echo "Conversion complete: $OUTPUT_FILE"
Save the file, for example, as convert_video.sh.
Make the script executable. You can do this from a terminal by navigating to the directory where you saved the script and then running:
bash
chmod +x convert_video.sh
To use the script by dragging and dropping a file on macOS, you might need an Automator app or similar, since drag-and-drop directly to a script isn’t a default behavior in macOS Finder:
Open Automator and create a new "Application."
Add "Run Shell Script" from the actions library.
Set "Pass input" to "as arguments."
Paste the path to your script in the command area followed by " "$@" (e.g., /path/to/convert_video.sh "$@").
Save the Automator application.
Now, you can drag and drop MP4 files onto the Automator application icon, and it will execute your script.
For Linux with graphical environments like GNOME, KDE, etc., you can often directly drag the file onto the script icon or a shortcut to the script.
This script checks if you've provided an input file, extracts the filename without its extension, constructs the output filename, and runs ffmpeg with your specified options. If the script fails at any command, it will stop executing due to the set -e command. This makes debugging easier if something goes wrong.