A Quick Introduction to Bash Programming
Preliminary Remarks
- A text editor allowing to process pure ASCII is needed. It’s important that no «smart» quotes are used, because they give syntax errors.
(I personally use since years BBEdit on macOS. The free mode is fully sufficient for our purpose.)
- It might be necessary to modify the permissions of the scripts we are going to program (
chmod +x).
Example 1
Problem
Let’s start with the classic «Hello, World» program.
Solution
#!/bin/bash
echo "Hello, Mars!"
Discussion
- #!/bin/bash
#! is called shebang. It tels to the computer that Bash is the programming language used. In the following examples we will use a more general shebang, but this older and shorter one is often still used.
- echo
- It’s good practice to always put into quotation marks what has to be printed on the terminal.
Exercices
- Use the general shebang:
#!/usr/bin/env bash
- Fix the planet’s name.
Example 2
Problem
Write a program that calculates the MD5 checksums for each frame in a file, by using the framemd5 function of ffmpeg. The filename with the extension and the path are transmitted to the program via a parameter.
Solution
#!/usr/bin/env bash
input_file="$1"
ffmpeg -i "$input_file" -f framemd5 "${input_file}_md5.txt"
Discussion
This specific FFmpeg command is to consider as a placeholder for almost any FFmpeg command we have seen during the workshop.
Exercices
- Modify the script in order to have the same filename as the transmitted file, but with the extension
.md5 instead as the original one.
- Write a Bash script that generates an H.264 file wrapped into an MP4 container from an audio-visual file.
- Write a Bash script that generates an H.264 file wrapped into an MP4 container from an audio-visual file, and that calculates the MD5 checksums of the new generated file at a frame level.
Example 3
Problem
Modify the program of example 2 in order to process all the files inside a folder.
Solution
#!/usr/bin/env bash
path_to_folder="$1"
files_in_folder="$(ls "$path_to_folder")"
for input_file in $files_in_folder; do
path_to_file="$path_to_folder/$input_file"
ffmpeg -i "$path_to_file" -f framemd5 "${path_to_file}_md5.txt"
done
Discussion
Each Bash command is a line of code. If for the readability of the code you wish to have more than one command in the same line, then they have to be divided by a semicolon (;).
Example 4
Problem
Modify the program of example 3 to process all the audio-visual files inside a folder, but not other kinds of files.
Example 5
Problem
Make the program of example 4 interactive and check that the passed parameters are valid ones.
Example 6
Problem
Add options to the program of example 4, and in particular a help menu.
2020-04-06
|