Course: Network and System Administration

In Class Lab: 11

Name: Introduction to shell scripting

Objective: Save commands in a shell script and run it like any other command. Create a script template, write scripts that take arguments, keep a log and make a simple decision with if, then save your scripts in your GitLab repository.

Since Lab 2 you have typed commands one at a time. In Lab 3 you joined them into one-liners with pipes, and in Lab 5 you saved their output with redirects. Each time you wanted to run them again, you pressed the Up arrow or typed them again.

A shell script is a text file of commands. The shell reads it from top to bottom and runs each line, just as if you had typed it. Write it once, and you can run it as often as you like, on any server, and share it with others. You already know every piece you need: Vim from Lab 4, redirects from Lab 5, chmod from Lab 6, variables such as $USER and $( ) from Labs 3 and 7, and Git from Lab 10.

Note: This lab is done on your development server, NOT your production server. Connect with SSH from Terminal or PuTTY and log in as your own user.

How to use the hints

Some steps give you every command. Others give you a Goal and ask you to work out the commands yourself. If you get stuck, open the hint. Once you have an answer, or if you are really stuck, open the solution and compare it with your own.

Lab overview

  1. Part 1: Your first script - Task 1
  2. Part 2: A template for every script
  3. Part 3: Pass arguments to a script - Task 2
  4. Part 4: Keep a log - Task 3
  5. Part 5: Make a decision with if - Task 4
  6. Part 6: Save your scripts in GitLab - Task 5

If you get stuck, check the Troubleshooting section at the end of this lab.


Part 1: Your first script

Create a workspace

Keep your scripts together in one directory. mkdir -p creates every directory in the path at once, as in Lab 10:

mkdir -p ~/scripts/shell cd ~/scripts/shell pwd

create scripts directory

Later labs copy files from ~/scripts/shell, so use this exact path.

Write the script

Create a file called first.sh with Vim:

vim first.sh

Press i, type these three lines, then press Esc and type :wq:

#!/bin/bash # My first script echo "Hello from $(hostname), I am $USER"
Line What it does
#!/bin/bash The shebang. It must be the very first line. It says which program runs the rest of the file. Here that is bash, the shell you have used since Lab 0.
# My first script A comment. The shell ignores any line that starts with #. Comments are notes for people who read the script, including you in three months.
echo "... $(hostname) ... $USER" A normal command. $(hostname) is command substitution from Lab 7, and $USER is the variable from Lab 3.

The .sh at the end of the name is not required. Linux doesn't care about file extensions, as you saw with file in Lab 0. It is there so people can tell at a glance that the file is a shell script.

Run it

There are two ways to run a script. Try the first:

bash first.sh

This starts bash and asks it to read first.sh. It works, but you want to run the script by its name, like any other command. Try that:

./first.sh ls -l first.sh

./first.sh fails with Permission denied. ls -l shows why: the permission string, such as -rw-rw-r--, has no x. In Lab 6 you learned that a file needs execute permission to be run as a program. Add it for yourself, the user who owns the file:

chmod u+x first.sh ls -l first.sh ./first.sh
Command What it does
chmod u+x first.sh Adds execute for the file's owner. ls -l now shows an x in the user's three letters, such as -rwxrw-r--, and the file name may turn green.
./first.sh Runs the script. ./ means "the file called first.sh in this directory".

Question: Why do you need the ./? Try first.sh on its own, and look at echo $PATH from Lab 2.

Answer

When you type a command name with no / in it, the shell only looks for it in the directories listed in $PATH, such as /usr/bin. It never looks in your current directory, so first.sh on its own gives command not found. This is a safety feature. Someone can't leave a script called ls in /tmp and have you run it by accident. ./first.sh is a path, so the shell runs exactly that file.

Task 1: Turn a one-liner into a script

In Lab 3, Task 2, you counted the login shells in use with a one-liner.

Goal: Write a script called shells.sh that prints a heading with the name of your server, then the count of each login shell in /etc/passwd. Make it executable and run it.

Hint
Solution
vim shells.sh
#!/bin/bash # Count the login shells in use on this server echo "Login shells in use on $(hostname):" cut -d: -f7 /etc/passwd | sort | uniq -c
chmod u+x shells.sh ./shells.sh
Login shells in use on itfdn-dev01.localdomain: 5 /bin/bash 1 /bin/sync 1 /sbin/halt ...

Your counts are different. Pipes work in a script exactly as they do at the prompt.

Going further: Redirects from Lab 5 work on a whole script, just as they do on a single command. ./shells.sh > shells-report.txt saves everything the script prints in one file.


Part 2: A template for every script

Every script you write should say what it is, who wrote it and why. A template is a file you copy to start each new script, so you never forget.

Create template.sh in ~/scripts/shell:

cd ~/scripts/shell vim template.sh

Add these lines. Leave the <...> placeholders as they are. You fill them in each time you copy the template:

#!/bin/bash # Title: <script_name>.sh # Date: <MM/DD/YYYY> # Author: <Your Name> # Purpose: <Describe script purpose> # Update: <Add update notes here>
Line What to put there
Title The script's file name.
Date The date you first wrote it.
Author Your name.
Purpose One sentence: what does it do?
Update A short note each time you change it, such as 10/30 added logging.

Everything after the shebang is a comment, so the template runs, but does nothing. You don't need to make it executable. You will add useful pieces to it in later labs.

Tip: The template's comments are a small version of what Git does in Lab 10: who, when and why. Git keeps the full history, but the header travels with the file, even when someone copies it to a server without Git.


Part 3: Pass arguments to a script

Most commands take arguments: ls /etc, chmod u+x first.sh. Your scripts can too. The shell puts each argument in a numbered variable called a positional parameter:

Variable Holds
$1 The first argument.
$2 The second argument, and so on.
$@ All of the arguments.

Create hello.sh from your template

cp template.sh hello.sh vim hello.sh

Tip: You can also pull the template into a file you already have open in Vim. In Normal mode, type :r template.sh and press Enter. Vim reads the file in below the cursor. In a new, empty file that leaves an empty first line, above the shebang. Press gg to go to the top, then dd to delete it. The shebang must be the very first line, or the script can't be run by name.

vim read in template

Fill in the header, then add the lines below it, so the whole file looks like this:

#!/bin/bash # Title: hello.sh # Date: <MM/DD/YYYY> # Author: <Your Name> # Purpose: Greet the user by name based on a single argument. # Update: # First argument is expected to be the name name=$1 # Display a greeting echo "Hello $name, pleased to meet you."
Line What it does
name=$1 Creates a variable called name, and sets it to the first argument. There are no spaces around the =.
echo "Hello $name, ..." To use a variable, put a $ in front of its name. The shell swaps $name for its value before echo runs, as you saw with $USER.

Make it executable, and run it with your name, then with no name:

chmod u+x hello.sh ./hello.sh angus ./hello.sh

hello script output

With no argument, $1 is empty, so name is empty, and you get Hello , pleased to meet you. The shell doesn't complain about an empty variable. You will learn to check for missing arguments in a later lab.

Note: The screenshot sets the permissions with chmod u=rwx,g=rx,o=. That is fine too. u+x is all you need.

Question: What does ./hello.sh Mary Jane print? Why? How can you get the script to greet Mary Jane?

Answer

It prints Hello Mary, pleased to meet you. The shell splits arguments on spaces, so Mary is $1 and Jane is $2, which the script ignores. Quotes keep spaces, as you saw with echo in Lab 2:

./hello.sh "Mary Jane"

Now $1 is Mary Jane.

Task 2: Look up a user

In Lab 3, Task 8, you found your own line in /etc/passwd with grep "^$USER:" /etc/passwd. In Lab 6 you created kthompson and rstallman.

Goal: Starting from your template, write a script called userinfo.sh that takes a username as its first argument. It should print that user's line from /etc/passwd, and then the user's groups. Test it with kthompson, rstallman and dritchie.

Hint
Solution
cp template.sh userinfo.sh vim userinfo.sh
#!/bin/bash # Title: userinfo.sh # Date: <MM/DD/YYYY> # Author: <Your Name> # Purpose: Show the passwd entry and groups for one user. # Update: # First argument is the username to look up user=$1 echo "passwd entry for $user:" grep "^$user:" /etc/passwd echo "Groups for $user:" id "$user"
chmod u+x userinfo.sh ./userinfo.sh kthompson ./userinfo.sh rstallman ./userinfo.sh dritchie
passwd entry for kthompson: kthompson:x:1002:1002:Ken Thompson:/home/kthompson:/bin/bash Groups for kthompson: uid=1002(kthompson) gid=1002(kthompson) groups=1002(kthompson),100(users),1003(research),1004(mentors)

Your numbers are different. The ^ and the : make sure grep matches the whole username at the start of the line, so ./userinfo.sh k doesn't print every user whose name starts with k.

Try ./userinfo.sh nobodyhere. grep prints nothing, and id prints no such user. The script carries on to the next line even when a command fails. You will learn how to stop a script when something goes wrong in a later lab.


Part 4: Keep a log

Scripts often keep a log: a file that records each time they ran. You already know how to add a line to the end of a file without losing the lines before it: >>, from Lab 5.

Open hello.sh again, and add these lines below the echo. Update the Update line in the header as well:

# Name of the log file mylog="hello.log" # Add every argument to the end of the log echo "adding args to the log" echo "$@" >> "$mylog"

hello script with log

Line What it does
mylog="hello.log" A variable holding the name of the log file. If you rename the log later, you only change this one line.
echo "$@" >> "$mylog" Prints every argument, and adds them to the end of the log. >> creates the file the first time.

Run it a few times, then read the log:

./hello.sh bob ./hello.sh "Mary Jane" ./hello.sh Mary Jane cat hello.log

hello log example

The greeting only uses $1, but the log keeps all the arguments, so the last run logs Mary Jane even though the greeting only said Mary.

Common Pitfall: Use >>, not >. With >, the log is emptied every time the script runs, and only ever holds the last line.

Question: Change to your home directory with cd, and run the script from there, with ~/scripts/shell/hello.sh alice. Where does alice get logged?

Answer

In a new hello.log in your home directory, not in ~/scripts/shell. hello.log is a relative path, from Lab 2. It is relative to the directory you are in when you run the script, not to where the script is saved. Check with ls ~/hello.log. To always log to the same file, give it an absolute path, such as mylog="$HOME/scripts/shell/hello.log". Change back with cd ~/scripts/shell before you go on.

Task 3: Add a date to the log

A log that only says bob isn't much use. A real log says when something happened, and who did it.

Goal: Change hello.sh so that each line in hello.log starts with the date and time, then the user who ran the script, then the arguments. Run it twice, and show the new lines in the log.

Hint
Solution

Change the last line of hello.sh to:

echo "$(date) $USER: $*" >> "$mylog"
./hello.sh bob ./hello.sh "Mary Jane" tail -n 2 hello.log
Fri Oct 30 10:15:02 PDT 2026 angus: bob Fri Oct 30 10:15:09 PDT 2026 angus: Mary Jane

$* is another way to get all the arguments. It joins them into one string, which is what you want inside a longer message like this. "$@" keeps them as separate words. Here both print the same thing. The difference matters when you work through the arguments one at a time, with loops, in a later lab.

Going further: date can print the date in any format you like. date "+%F %T" prints 2026-10-30 10:15:02, which sorts in the right order. See date --help.


Part 5: Make a decision with if

So far your scripts run every line, every time. An if statement runs some lines only when a test is true.

Create greetings.sh

cp template.sh greetings.sh vim greetings.sh

Fill in the header, and add the lines below it:

#!/bin/bash # Title: greetings.sh # Date: <MM/DD/YYYY> # Author: <Your Name> # Purpose: Greet a user based on the argument provided. # Update: if [ "$1" = "night" ]; then echo "Good evening" exit 0 fi # Default response if argument does not match echo "Good day"

greetings script

Part What it does
if [ ... ]; then Runs the test in the square brackets. If it is true, run the lines up to fi.
"$1" = "night" The test: is the first argument exactly the word night? A single = inside [ ] compares two strings.
exit 0 Stops the script now. The lines below it are not run. 0 means "finished with no errors".
fi The end of the if. It is if backwards.
echo "Good day" Only reached if the test was false, because a true test exits first.

Make it executable and test every path through the script:

chmod u+x greetings.sh ./greetings.sh night ./greetings.sh morning ./greetings.sh Night ./greetings.sh

Only night gets Good evening. Night gets Good day, because the comparison is case sensitive, just like file names in Lab 0.

Common Pitfall: The spaces matter. [ is actually a command, and "$1", =, "night" and ] are its arguments. Like any command, its arguments need spaces between them. if ["$1" = "night"] fails with an error such as [night: command not found. Keep the double quotes around "$1" too. Without them, an empty $1 leaves [ = night ], and you get unary operator expected.

Task 4: Add a help message

Most commands print a short usage message when you ask for help, as you saw with --help in Lab 0.

Goal: Add a second if block to greetings.sh. When the first argument is help, print a usage line and a one line description, then stop without printing Good day. Test it with help, night and morning.

Hint
Solution

Add this block above the night block, after the header:

if [ "$1" = "help" ]; then echo "Usage: ./greetings.sh [night|help]" echo "Description: Displays a greeting based on the time of day." exit 0 fi

greetings with usage

./greetings.sh help ./greetings.sh night ./greetings.sh morning

The help block can go anywhere above the final echo "Good day". If you put it at the bottom, the script prints Good day and never reaches it. Putting help first is the usual habit: anyone reading the script sees how to use it straight away.

The [night|help] in the usage line is a common way to write "one of these words". The square brackets mean the argument is optional, and | means "or".

Going further: Every command leaves an exit status behind, and $? holds the status of the last one. 0 means success, and anything else means something went wrong:

./greetings.sh help echo $? ls /nosuchfile echo $?

The first prints 0, the value you gave to exit. ls prints 2. You will use exit statuses to make decisions in a later lab.


Part 6: Save your scripts in GitLab

In Lab 10 you created a GitLab repository to keep your work from later labs. Your scripts belong there: if your development server is lost, your scripts are not.

Get ready

Start an agent and load your dev01 key, as in Lab 10, Part 6. Then change into your repository, and git pull first, as you learned in Lab 10, Task 7:

eval "$(ssh-agent -s)" ssh-add cd ~/git/gitlab/itfdn-140-inclass-$USER git pull

Copy, commit and push

Keep the same layout in the repository as in your home directory, so you always know where a script came from:

mkdir -p scripts/shell cp ~/scripts/shell/*.sh scripts/shell/ ls -l scripts/shell git status git add scripts/shell git commit -m "add lab 11 shell scripts" git push git log --oneline
Command What it does
cp ~/scripts/shell/*.sh scripts/shell/ Copies every file ending in .sh, with the wildcard from Lab 2. The log files are left behind. They don't belong in Git.
ls -l scripts/shell The copies keep their x permission. cp copies it from the original file.
git add scripts/shell Stages the whole directory at once.
git commit Shows create mode 100755 for each script you made executable. Git saves the x permission too. 100644 means not executable.
git push Sends the commit to GitLab. Your branch is main, from Lab 10.

In GitLab, open your project and click scripts, then shell. Your scripts are there, with your header comments.

Task 5: Change a script, then push the change

These are copies. When you change a script in ~/scripts/shell, the copy in your repository doesn't change until you copy it again.

Goal: Change greetings.sh in ~/scripts/shell so that it also answers morning with Good morning, and note the change in its Update line. Test it. Then copy it to your repository, show exactly what changed before you commit, and commit and push the change.

Hint
Solution
cd ~/scripts/shell vim greetings.sh

Add this block above the final echo "Good day", and update the header, for example # Update: added morning:

if [ "$1" = "morning" ]; then echo "Good morning" exit 0 fi
./greetings.sh morning cp greetings.sh ~/git/gitlab/itfdn-140-inclass-$USER/scripts/shell/ cd ~/git/gitlab/itfdn-140-inclass-$USER git diff git add scripts/shell/greetings.sh git commit -m "greetings.sh: answer morning" git push git log --oneline

git diff shows your new Update line and the new if block, each line with a + in front.

When you have finished with Git for today, stop your agent with eval "$(ssh-agent -k)", as in Lab 7.


Lab summary

You have now:

Questions to consider

Discuss these with others in class:

  1. Why does bash first.sh work without x permission, when ./first.sh doesn't?
  2. Why doesn't the shell look in your current directory for commands? What could go wrong if it did?
  3. What would happen if #!/bin/bash was the second line of a script, under a blank line?
  4. hello.sh logs to a relative path. Where would its log end up if it was run from a scheduled job, with no one logged in? Why is an absolute path safer?
  5. Which commands from Labs 2 to 10 would you like to have in a script? What would the script's arguments be?
  6. Why keep scripts in Git, rather than only in your home directory?

Troubleshooting

Q. ./hello.sh says "Permission denied".

A. The script isn't executable. Run chmod u+x hello.sh, then check for an x with ls -l hello.sh.

Q. hello.sh says "command not found".

A. Put ./ in front of the name, as in ./hello.sh. The shell only looks for commands in the directories in $PATH. Also check that you are in ~/scripts/shell with pwd.

Q. I get "bad interpreter: No such file or directory", and the message mentions ^M.

A. The script has Windows line endings, as in the Lab 8 troubleshooting section. This happens if you wrote it in Notepad, or copied it from Windows. Remove the extra characters, then run the script again:

sed -i 's/\r$//' hello.sh

Q. I get "bad interpreter", but there is no ^M.

A. Check the first line with head -n 1 hello.sh. It must be exactly #!/bin/bash, with no spaces before it and no empty line above it. A common typo is #!/bin/bsh or #/bin/bash.

Q. I get "name: command not found".

A. There are spaces around the =. name = $1 asks the shell to run a command called name. Write name=$1, with no spaces.

Q. I get "[night: command not found" or "[: missing `]'".

A. There is a missing space inside the square brackets. It must be [ "$1" = "night" ], with a space after [ and before ].

Q. I get "unary operator expected".

A. $1 was empty, and isn't in double quotes. Write "$1", not $1, inside [ ].

Q. I get "syntax error: unexpected end of file".

A. An if is missing its fi. Each if needs a fi of its own.

Q. ./greetings.sh night always prints "Good day".

A. Check the spelling and case of night in both places. If you copied the script from a web page or a document, check for curly quotes, such as “night”, in place of straight quotes, "night". The shell treats curly quotes as part of the word. Retype them in Vim.

Q. hello.log is empty, or only has one line.

A. Check that the echo line uses >>, not >. Also check that you are looking at the right hello.log. It is created in whichever directory you ran the script from.

Q. git push or git pull says "Permission denied (publickey)".

A. Your agent isn't running, or your key isn't loaded. Run eval "$(ssh-agent -s)" and ssh-add, then try again. See the Lab 10 troubleshooting section for more.

Q. cd ~/git/gitlab/itfdn-140-inclass-$USER says "No such file or directory".

A. Your repository has a different name, or you haven't cloned it on this server yet. See Lab 10, Part 7, and the troubleshooting entry about renaming your project.

If you can't solve a problem, post it in this week's Teams channel, or reach out by email for help.


Lab complete