How I started writing shell scripts


As a developer, we use the CLI a lot for various things, and as someone who has to probably learn about computers, it is highly recommended to have some understanding about CLI and it’s capabilities.

For me, it all started when I was trying to work with ffmpeg and the bash shell to iterate through a number of mp4 files and extract their audio in mp3 files. The idea was, to take each item with the .mp4 file format in the current directory and execute the following code for each of these items: ffmpeg -i filename.mp4 filename.mp3. In simple words, just take the file with the name filename which is of the mp4 format and convert it to mp3 format. I wrote a useful piece of code to do it in the bash shell itself, and it was this: for file in *.mp4; do ffmpeg -i "$file" "${file%???}mp3"; done;. The ones who are familiar with bash shell probably know this and are cringing at it, but it simply means this: “for” every item which matches with .mp4 in the end (*.mp4), reference to such an item as “file” and do (or execute) ‘ffmpeg -i “$file” “${file%???}mp3’. Here, “$file” means the item with “.mp4” in the end and “${file%???}mp3” means remove the last three items (or in this case, letters) from “$file” and attach “mp3” to the remaining string.

For the longest time, I had this command saved somewhere for any rainy day when it would be needed. Just copy pasting it in the CLI. Then I thought about it and figured, there must be a way to automate this. Sometime later, I came across the fact that you can write proper scripts and save them in files, just like writing code in a particular language and saving it in the given file format. I started with some very basic programs and operations, played with the shebang operator. It was good times. In the end, I finally wrote the following script to automate this and saved it as a binary executable in my bash_profile.

#!/bin/bash
mkdir -p output
for name in *.$1; do
ffmpeg -i "$name" "output/${name%.*}.$2"
done

Definitely an upgrade over the previous one and much more scalable. I replaced a couple of parameters and named this script as ffmpegrec. So the usage for this script is ffmpegrec <input format> <output format>.

Without even realising at the moment, this was my very first script which automated some mundane yet essential processes for me. A couple of years down the line, I am a fan of the bash shell trying to work my way through various tasks a developer. Surely, there are a number of benefits to knowing and automating your work using whatever script you use, there are a number of them to choose from with little to no differences.

Some references you can use:

,

Leave a Reply

Your email address will not be published. Required fields are marked *