Bash scripting from scratch
Scripts that read input, branch, loop, fail loudly and drive other programs — with the quoting and redirection rules that trip everyone up.
Bash glues a Linux system together: it starts programs, connects their inputs and outputs, and automates whatever you would otherwise type by hand. It is also a language with unusual rules. Variables are expanded into words before a command runs, if tests the exit status of a command rather than a boolean, and a script happily carries on after an error unless told otherwise.
This course follows the repository’s small scripts and explains those rules where they matter. Two of the live animations show what Bash actually does with a command line — how redirections rewire file descriptors, and what [ $num -gt 0 ] becomes when num is empty.
Prerequisites
A Linux or macOS terminal. Lesson 5 runs a Python script, so Python 3 with NumPy, SciPy and Matplotlib helps.
Running the code
cd bash_scripting_from_scratch
bash control_flow_for.sh # run with bash explicitly
chmod +x control_flow_for.sh # or make it executable once...
./control_flow_for.sh # ...and let the #!/bin/bash line choose bash
ShellCheck is worth installing alongside: it catches most of the quoting problems discussed here before they bite.
Lessons
- 1 Input, output and redirectionecho, read and command substitution — then the three file descriptors every program has, and how > , 2>&1 and | rewire them.
- 2 Conditions, test and caseif runs a command and branches on its exit status — which is why an empty answer is reported as zero.
- 3 Loopsfor over a list, while with arithmetic, and why {1..$n} does not do what it looks like.
- 4 Exit statuses and debuggingTracing scripts with set -x, reading $? at the right moment, and making scripts stop at the first error.
- 5 Driving a Python program from BashA launcher script that sets up and runs a Bézier curve fit — and how to make it work on any machine.