CS计算机代考程序代写 CS246-F20-01-UnixShell

CS246-F20-01-UnixShell

Lecture 1.17

• Writing bash scripts
– Two examples

CS246

An example

• Payday is on the last Friday of the month; print the
date of this month’s payday
– We’ll use the UNIX command cal as a helper

• There are 2 tasks:
1. Compute the date
2. Present the answer

#!/bin/bash

report() {
# Inside a fcn, $1, etc. denote the *fcn’s* params
if [ $1 -eq 31 ]; then

echo “This month: the 31st” # not perfect, just fun
else

echo “This month: the ${1}th”
fi

}

# Compute the date; pass as argument 1 to the “answer” routine
# cal with no args prints calendar of current month
# The call to awk picks the sixth token in each line
# egrep filters out non-numbers
# tail -1 gives us the last number
report $(cal | awk ‘{print $6}’ | egrep “[0-9]” | tail -1)

Another example

• Now, let’s generalize this script to work for any
month of any year

• We note that cal May 2016 gives the calendar
for May 2016 …
– … so we can let ./payday May 2016 give May 2016’s

payday

#!/bin/bash

report() {
if [ $2 ]; then

# $2 (2nd argument) is the month, if supplied
# -n suppresses the trailing newline
echo -n $2

else
echo -n “This month”

fi

if [ $1 -eq 31 ]; then
echo “: the 31st” # not perfect, just fun

else
echo “: the ${1}th”

fi
}

report $(cal $1 $2|awk ‘{print $6}’|egrep “[0-9]”|tail -1) $1

# Note that arg $2 in report is the same as arg$1 in the main
# script, as $1 was passed as the second argument to report.

End

CS246

1. Some notes on OSs,
UNIX, and the UNIX shell

CS246 Fall 2020

Prof. Mike Godfrey
University of Waterloo