Note: As I balance professional work with personal projects, my available time is limited. Nevertheless, I hope this content clearly shows my enthusiasm for Linux and software development. Thank you for your understanding.

Thursday, April 2, 2026

Programming Scripting Automation: PART I (INTRODUCTION) Batch Video Conversion with Bash Loop and FFmpeg

FFmpeg compressing a video.

    Hello guys, good evening. Today I want to share a simple Bash scripting trick to automatically convert videos from the current directory where the script is placed.

I usually use this script to compress videos before storing them on my old phone, so they don’t take up too much storage.

Let’s get started.


The Bash Script


for f in *.mp4; do
    ffmpeg -i "$f" -vcodec libx264 -crf 27 -preset fast -b:v 1M "${f%.mp4}_compressed.mp4"
done

Explanation:

1. for f in *.mp4; do

This will loop everything in the current directory and find only the .mp4 file format to be executed in loop. 

2. ffmpeg -i "$f" -vcodec libx264 -crf 27 -preset fast -b:v 1M "${f%.mp4}_compressed.mp4" 

- ffmpeg, the program that runs the video tool.

- i "$f", input file "video.mp4"

- vcodec libx264, use H.264 codec to compress.

- crf 27, its quality level and higher number is smaller size of the compressed video.

-  preset fast, encoding speed faster encode same as bigger file.

-  b:v 1M, video bitrate is 1 Mbps

- "${f%.mp4}_compressed.mp4", the output filename is the original name with _compressed.mp4

3. done

- Every loop in Bash must end with the done keyword.


Saving And Running

Save the file with anything you mean, but here I save the script file with "AutoCompress.sh".

Before you can do the automate compress with this script you need to add the execute permission to the file with: 


chmod +x AutoCompress.sh

Now you can run with:


./AutoCompress.sh

Running the scrip.


Progress of compressing video.

 

Video is compressed.

End

Well, that's all I can share and thank you very much for visiting my blog. I hope to see you again soon!