Day 4: Clean-up and Review

Some days I just need to review what I have done and today was that day. The past two days had me struggling through my first real shell scripting exercises. The experience was great but also a bit jarring. Today really helped me solidify some of the key concepts I covered.

TLDR;

Okay, so here are the highlights of what I did:

  • Reviewed my solution for exercise 3 from MIT Missing Semester Course.
  • Looked into the meaning of >&2 in and other similar output redirection commands in the shell.
  • Started Listening to the Command_Line Heroes episode on the history of the shell.

Input / Output Syntax from Exercise 3

Here is the problem from the lecture:

Say you have a command that fails rarely. In order to debug it you need to capture its output but it can be time consuming to get a failure run. Write a bash script that runs the following script until it fails and captures its standard output and error streams to files and prints everything at the end. Bonus points if you can also report how many runs it took for the script to fail.

#!/usr/bin/env bash

 n=$(( RANDOM % 100 ))

 if [[ n -eq 42 ]]; then
    echo "Something went wrong"
    >&2 echo "The error was using magic numbers"
    exit 1
 fi

 echo "Everything went according to plan"

I initially struggled with:

>&2 echo "The error was using magic numbers"

I could not understand what >&2 was doing but after some review I realized that the command can be broken into two parts:

  • > refers to the standard output redirection command.
  • &2 refers to the current output location for standard error output.

In summary the echo standard output was being redirected to the same current location of the standard error output.

Conclusion

That’s all for today. Btw if you are interested in the MIT course you can check out the video lecture I’m currently doing the exercises for. The lecture is helpful but isn’t sufficient by itself. Anyways, until next time PEACE!

YouTube player