Day 3 thumbnail

Day 3: Writing a Logging Script is not a Joke

The third day into the round and I’m getting faster with my blogging process. I’m still struggling but I’m improving my process so that I can just share and not structure as the days continue to progress.

TLDR;

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

  • Solved exercise 3 from MIT Missing Semester Course which was AGAIN not easy for me lol.
  • looked into how to write a do-while loop in a shell/bash script.
  • Searched for docs on I/O redirection syntax and examples for my personal notes.

Exercise 3 Solution

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"

My solution looked like this:

#!/usr/bin/env bash

function tester {
    echo -e "----------\n$(date)\n" | tee log.txt error.txt
    local test_count=1
    while
        # Pass in the script that needs to be tested as argument 1
        echo "Test $test_count:" >> log.txt
        "$1" 1>> log.txt 2>> error.txt
        local error_code=$?

        echo -e "Error code: $error_code\n" 1>> log.txt 2>> error.txt
        test_count=$(( $test_count + 1 ))
    [[ $error_code -eq 0 ]]; do :; done

    tail log.txt error.txt
    echo "Number of tests: $test_count"
}

The Difficult Part

So, I really struggled with managing the input of the given script and then sending it’s output to either the log.txt or error.txt files. This symbol ( >&2 ) in particular threw me for a loop.

I somehow threw it all together but I am still not comfortable with my level of understanding of my own code lol.

do-while Loops in the shell/bash

Technically there is no actual do-while loop but with a certain syntax we can get the same functionality.

while statements; test do :; done

I actually used this format in my solution which I was pretty proud of. I learned this from a StackOverflow question.

I/O redirection syntax

Since this particular aspect of my code was very difficult for me I thought I should look for some material so that I could study it a bit more. This is still a work in progress lol. Maybe tomorrow will be better.

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!