Lab 4: Advanced Scripting

Exercises:

This lab carried on from the last lab in teaching bash scripting. We were introduced to more advanced concepts.

  1. We learned about functions in bash. There are two ways to declare functions. Note that in bash, everything is global by default. Functions therefore don't necessarily have to return anything and one can just assign to global variable. To access parameters passed to functions, use $1, $2, $3, etc. $0 is the function itself.
    function my_function {
     # stuff here
    }

    my_function () {
     # stuff here
    }
  2. Learning about redirection, ls -l > file.txt, which will store the output from ls -l into that file. Or using >> to append instead of overwrite.
  3. Piping, using the pipe | character, redirects (or pipes) the output from the first command through the second. For example, ps -a | wc -l will get the output (a list of all processed) and put it through a count command which counts the number of lines, and that gets output.
  4. Using pattern matching (a form of regex which is NOT regex) to filter out things. One example is using cat /usr/share/dict/words | grep "^..ing$" to print out all 5 letter words ending with "ing" to the console. Or, one can use find and replace (with sed), such as echo "x is 5 plus 6" | sed "s/plus/+/g" which will print out "x is 5 + 6".
    Additionally, a command to list all world readable files goes something like ls -l | grep "^.r..r..r.*$".
  5. Making a Fibonacci generator bash script (linked below).

References:

Reflections:

First of all, I should remark that global-by-default is horrifying. The function system is not particularly intuitive (what with implicit passing of parameters) but tolerable, and with difficulty I did manage to make a fibonacci script. Things similar to this however may be my limit with this language.

With added regex on top, scripting becomes even harder to do. Regex is renowned as being hard to understand/use and it is no different here. However, this lab was a fairly gentle introduction to pattern matching, and with a cheat sheet I am able to manage simple regex tasks.

Back