CIS-2230 Lab #5: Shell Scripts

In this lab you will experiment with a basic shell script.

Part 1: Create a Test User

For this part of the lab, you will create a new user account on the system. You can log in as this user to check the script you will write/modify later. You can give this user any name you like. I'm using "jjones" (for Jill Jones) in the example below:

  $ sudo adduser jjones

To verify your user, create a second connection with your virtual machine and log in as your new user. You can use the who command to see who is logged into the system.

Part 2: watch.sh

Download the watch.sh script and transfer it to your virtual machine. Make the script executable using the command:

  $ chmod +x watch.sh

Run the script to watch for login activity of your new user. Try logging in and out as that user a few times to see the effect. Note that by default watch.sh only checks the list of logged-in users every 10 seconds (but that can be changed using the -d option).

Try specifying a log file (-f option), and activate "silent" mode (-s option). In this case, the script should display nothing but instead write to the log file.

Part 3: Modify watch.sh

Make the following modifications to the script.

  1. Right now the script outputs a "marking time" line whenever it examines the list of logged-in users even if there is no relevant change to the user being watched. While this shows the script is active, it can produce a lot of "noise" in the output. Modify the script so that it only prints the marking time line if a new -m option is provided.

  2. Modify the script so it captures the login time and the logout time and then, when the user logs out, displays how long the user was logged in. Hint: You might find the following helpful:

      t1="17:42"  # Example logout time.
      t2="12:50"  # Example login time.
    
      # Convert to minutes since the epoch.
      m1=$(( $(date -d "$t1" +%s) / 60 ))
      m2=$(( $(date -d "$t2" +%s) / 60 ))
    
      diff=$(( m1 - m2 ))
    
      # Compute hours and minutes of the time difference (from minutes)
      hours=$(( diff / 60 ))
      mins=$(( diff % 60 ))
    
      # Displays "4:52", meaning 4 hours, 52 minutes between 17:42 and 12:50.
      printf "%02d:%02d\n" "$hours" "$mins"
    

Submission

For this lab, submit your modified script. The lab is worth 20 points.


Last Revised: 2025-09-26
© Copyright 2025 by Peter Chapin <peter.chapin@vermontstate.edu>