#!/bin/sh

# This file is a «shell script». Lines starting with ‹#› are
# comments, while everything else in the file are commands. Commands
# in a shell script work the same like they do in a command line.
# Make sure you are in your ‹~/pb152/01› (you can use ‹pwd› to
# check).

# You can «run» this script (the file that you are currently
# reading) by typing this command (you should probably do that in
# your other terminal):
#
#     $ sh files.sh
#
# Doing that is the same as typing all the commands listed in this
# file one by one. Shell scripts are very useful when you find
# yourself typing a long sequence of commands over and over again.
# This happens when compiling C programs, for instance. We will look
# at the C compiler next week, and then at automating it in two
# weeks.
#
# For now, we will demonstrate some of the things that shell scripts
# can do.  First, we will run some of the commands we already know:

mkdir scratch
cd scratch
cp ../intro.txt .
cp ../../00/grading.txt .

# The above two commands copied two of the text files you have seen
# earlier into our working directory. Let's also copy this shell
# script:

cp ../files.sh .

# You may remember ‹echo› from earlier, too. Let's tell the user
# that we did something:

echo "we are done copying the files"
echo

# Let's look at something new. You remember ‹ls› which lists files.
# We can list individual files too, instead of entire directories:

echo listing just files.sh
ls files.sh
echo

# Now we will use something called ‘globbing’ -- we will refer to
# multiple files with a shorthand, using the character ‹*›:

echo listing all text files
ls *.txt
echo

# One of the useful commands that we didn't mention yet is ‹head›,
# which prints a few lines from a given file. We can tell it how
# many we want using ‹-n›.  You can learn more, as usual, in ‹man
# head›.

echo first line of intro.txt
head -n 1 intro.txt
echo first line of grading.txt
head -n 1 grading.txt
echo

# Sometimes, we want to run some commands for multiple files. We
# could type them out, like we did above. But often, we can use a
# loop instead. In Python, you would write a ‹for› loop. We can do
# something similar in a shell script:

for f in *.txt; do
    echo "first line of $f (in a loop)"
    head -n 1 $f
done
echo

# Notice that we used double quotes in the ‹echo› this time. That is
# because parentheses are special to the shell, but we just want to
# print them. When you want to print something and you are not sure
# whether it contains special characters, use double quotes. They
# won't hurt if they are not required.

echo "no double quotes were needed here"
echo

# Since this script is getting long, we will stop and continue in
# another one.  Let's first clean up the files though:

rm intro.txt grading.txt files.sh
cd ..
rmdir scratch

# Now you can finally do an exercise for yourself. Let me give you
# the instructions right away:

echo that is all, instructions for an exercise follow
echo
cat 1.txt
