teaching machines

CS 330 Lecture 2 – Hello, Shell

Agenda

  • what ?s
  • some shell exercises
  • tell me something you know about the shell
  • the UNIX way

TODO

  • Set your homework repository.
  • Read Shell Programming with Bash.
  • 1/4 sheet: share 3-4 questions or observations about shells or Bitbucket. I offer you some optional challenge problems, which may be solved with one line of shell code:
    • You are a web server administrator. Make all files in /var/www (even those in subdirectories) readable to others. If the files are executable by the user/owner, also make them executable by others.
    • Read a file of text, determine the  n most frequently used words, and print out a sorted list of those words along with their frequencies.
  • Optional: check out Zsh.

Questions

  • What’s the purpose of the shell? What’s something you might want to do with a shell script that isn’t as easy in another language?
  • Does the shell have a means of persisting data?
  • Does the shell support expressions?
  • Does the shell support types?
  • Does the shell have a mechanism for abstracting code?
  • Does the shell have a mechanism for passing data around?
  • Does the shell have a standard library?
  • How are errors handled?
  • What’s different about a shell script vs. C code?

Code

fixext

#!/usr/bin/env zsh

newext=$1
shift

for i in $@; do
  yes | mv $i ${i:r}.$newext
done

safe_rm

#!/usr/bin/env zsh

trash=$HOME/.junkies

mkdir -p $trash
for i in $@; do
  mv $i $trash/${i:t}.$RANDOM
done

bigs

#!/bin/sh

du | sort -nr | head -n 20

massmail

#!/usr/bin/env zsh

for i in $(cut -f2 -d, grades.csv | sed 1d); do
  echo "Delete this email." | mail -s "[CS 330] Real Good Deal on Chronometers" $i@uwec.edu
done

dirdiff

#!/usr/bin/env zsh

d1=$1
d2=$2

for i in $d1/*; do
  basename=${i:t}
  if [[ ! -e $d2/$basename ]]; then
    echo "No $basename in $d2!"
  elif [[ -d $i ]]; then
    $0 $i $d2/$basename
  else
    diff $i $d2/$basename >/dev/null
    if [[ $? -ne 0 ]]; then
      echo "Files $i and $d2/$basename differ."
    fi
  fi
done

Haiku

on simplicity and complexity:
UNIX has two ways
Do one thing and do it well
Be “glueser”-friendly

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *