Shell and Unix Notes
Shell and Unix Notes
and Unix
1.1 Introduction
In the lab, we provide dual-boot machines, which can be used as Windows or Linux. Typically, you
won’t be doing the activities under Windows; instead you will need to reboot the machines into Linux.
Because of the setup involved, in providing the environment for you in the lab, the login can be very
slow (especially the first time you login at a particular machine). So, as soon as you enter the lab for
your weekly session, start your login. This uses your UniKey username and password (the same as you
use for eLearning, Sydney Student and other facilities; for most students, the username consists of four
letters and four digits).
You are welcome to use your own laptop and connect to the University’s wireless network instead of
a lab machine, as long as it is running a version of Unix (eg MacOS or the Linux subsystem for
Windows 10). Please note: in that case any admin support or troubleshooting is up to you.
This (and many other labs) have a lot of information; they are intended to be kept as a reference as well
as instructions during the session. Most labs end with a capability checklist, that points you to the
crucial aspects that you really should practice and remember.
$ COMMAND
To execute the command above be sure to only type COMMAND, then enter. Don’t type the $
character, this is only a prompt to indicate you can type a command..
$ cat /proc/uptime
37931.26 37812.78
$ cat /proc/uptime
37932.72 37814.24
Notice, every time you run the program the numbers are changing. To give you an idea of what the file
contains, try running the uptime command, which tells you how long the machine has been running (or
up) for (in this case about 10.5 hours)
$ uptime
00:27:44 up 10:33, 2 users, load average: 0.00, 0.00, 0.00
1.5.1 pwd
Each process (a running program) has a working directory (also called the current working directory)
from which all relative paths are interpreted.
The pwd command prints the current path and thus enables you to work out where you are in the
filesystem. For example, if you run pwd when you first log in, you will find you are in your home
directory:
$ pwd
/home/bgat5227
$
On linux, user accounts are usually given home directories of the form: /home/<login> where
<login> is your UniKey login name.
1.5.2 ls
When you first login, your current working directory is your home directory. Your home directory has
the same name as your username, for example, bgat5227 for the lecturer’s account, and it is where
your personal files and subdirectories are saved.
To find out what is in your home directory, type:
$ ls
Downloads Favorites MyMusic MyPictures MyShapes MyVideos
$RECYCLE.BIN
$
ls is an example of a command which can take options: -a is an example of an option. The options
change the behaviour of the command. There are online manual pages that tell you which options a
particular command can take, and how each option modifies the behaviour of the command. (See later
in these lab notes)
1.5.3 mkdir
We will now make a subdirectory in your home directory to hold the files you will be creating and
using in this lab. To make a subdirectory called unixstuff in your current working directory type:
$ mkdir unixstuff
$ ls
Downloads Favorites MyMusic MyPictures MyShapes MyVideos
$RECYCLE.BIN unixstuff
1.5.4 cd
The change directory command cd <directory>, changes the current working directory to
<directory>. The current working directory may be thought of as the directory you are “in”, i.e. your
$ cd unixstuff
Type ls to see the contents (which should be empty) and pwd to see the absolute path.
$ ls
$ pwd
/home/bgat5227/unixstuff
$ pwd
/home/bgat5227/unixstuff
$ cd .
$ pwd
/home/bgat5227/unixstuff
$ cd ..
$ pwd
/home/bgat5227
$ pwd
/home/bgat5227
$ mkdir foo/bar
mkdir: cannot create directory 'foo/bar': No such file or directory
$ mkdir unixstuff/backups
$ ls unixstuff
backups
$ mkdir -p foo/bar
$ ls foo
bar
We cannot create nested directories (directories within other directories) without first creating the
necessary parent directories. The -p option can be used to force the building of parent directories first.
Now we have two directories within our home directory (unixstuff and foo). The unixstuff directory
has a backups subdirectory, and foo has a bar subdirectory.
$ ls backups
ls: backups: no such file or directory
$
We can’t see inside the backups directory directly from our home directory, because it is only
accessible from inside the unixstuff directory. However, we explicitly put parent directories using
slashes (a relative path) like:
$ cd unixstuff/backups
$ pwd
/home/bgat5227/unixstuff/backups
$ ls ..
backups
$ ls ../..
Downloads Favorites foo MyMusic MyPictures MyShapes MyVideos
$RECYCLE.BIN unixstuff
$ ls ../../foo
Notice we can also use the .. directory with the slashes to get access to the grandparent directory,
and then other directories from there.
~ (the tilde) is another special directory that represents your home directory.
1.6.1 cp
This is used to copy a file or directory to a new location:
$ cd ~
$ touch afile
$ ls
afile Downloads Favorites foo MyMusic MyPictures MyShapes MyVideos
$RECYCLE.BIN unixstuff
$ cp afile unixstuff
$ ls unixstuff
afile backups
$
touch is used to create an empty file (containing no characters), but you could create a file like this
just as easily with a text editor (e.g. try using nano: nano afile, it’s good for quick and easy text editing,
but not for longer more complex editing sessions).
Here we have copied the file afile into the unixstuff directory. So now a copy of afile exists in
your home directory and also in the unixstuff directory.
The file can also be copied to different filenames. Here we make a copy of afile called
anotherfile:
$ cp afile anotherfile
$ ls
afile Downloads foo MyPictures MyVideos unixstuff
anotherfile Favorites MyMusic MyShapes $RECYCLE.BIN
As well as specifying a named directory, you can also copy files to the current directory using dot:
If we want to copy directories and all of their subdirectories recursively, the -r flag should be used:
$ cd
$ cp -r unixstuff moreunixstuff
$ ls moreunixstuff
afile anotherfile backups
$
Notice that the cd command without a directory argument returns you to your home directory (just
like cd ~). We have then created a complete copy of unixstuff and its subdirectory backups.
1.6.2 mv
This is used to move (or rename) files and directories. Note, unlike MSDOS and the Windows
command shell (cmd.exe) there is no separate rename command:
$ ls
afile Downloads foo MyMusic MyShapes $RECYCLE.BIN
anotherfile Favorites moreunixstuff MyPictures MyVideos unixstuff
$ mv afile foo
$ mv anotherfile yetanotherfile
$ mv moreunixstuff lessunixstuff
$ ls
1.6.3 rm
This is used to delete files.
$ ls
Downloads foo MyMusic MyShapes $RECYCLE.BIN yetanotherfile
Favorites lessunixstuff MyPictures MyVideos unixstuff
$ rm yetanotherfile
$ ls
Downloads foo MyMusic MyShapes $RECYCLE.BIN
Favorites lessunixstuff MyPictures MyVideos unixstuff
$
Here we have deleted the file yetanotherfile. NB: unlike Windows there is no trash can under
Unix, once a file is deleted it is gone forever. The only way of getting back a file is to have a backup
copy of it somewhere else on the system.
$ rm lessunixstuff
rm: lessunixstuff is a directory
$ rm -r lessunixstuff
$ ls
Downloads Favorites foo MyMusic MyPictures MyShapes MyVideos
$RECYCLE.BIN unixstuff
$
We cannot use this to delete directories unless we use the -r flag. Be careful using this as it will
delete everything in that directory, i.e. all of the subdirectories and the files they contain.
1.6.4 rmdir
This is used to delete directories. It will only work when they are empty.
$ rmdir foo
rmdir: directory "foo": Directory not empty
$ rm foo/afile
1.7.1 clear
This command will clear the screen and is sometimes useful when viewing files or listing lots of
directories. It doesn’t clear the entire history, only the current screenful. Commands prior to that will
still be visible if you scroll the terminal window up.
1.7.2 cat
This will print the given file(s) to the standard output (screen).
$ cat /usr/share/dict/words
1080
10-point
...
zZt
ZZZ
$
You should have seen a lot of words fly by on the screen with this command. That’s because
/usr/share/dict/words contains a list of standard English words.
Note that /usr/share/dict/words is sometimes found at /usr/dict/words, particularly on
older Linux installations, and they can contain very different sets of words. Or if you are using Ubuntu,
you may need to install the wamerican or wbritish package to get access to the words file using
sudo apt-get install wamerican wbritish.
If multiple files are given, they will be printed one after the other in order.
$ less /usr/share/dict/words
1080
10-point
10th
...[to end of page]
$
1.7.4 grep
grep prints lines of the input matching a given expression:
xanth-
xanthaline
...
$ grep -i 'ˆx' /usr/share/dict/words
X
x
X25
XA
xalostockite
...
$
grep is case sensitive by default, so we have to use the -i flag to set case insensitivity. Other useful
flags are -v (line that do not match) and -c (produce a count only). If multiple files are given then
the results are given by file.
More complex expressions can be used for the pattern, including wildcard characters. These include:
● * (0 or more of the preceding character),
● . (any character),
● [abc] (any 1 of the included characters),
● [ˆabc] (any 1 character, except those included),
● ^ (if put at the start of a pattern, specify that the string must start with the match)
● $ (if put at the end of a pattern, specify that the string must end with the match)
When used (or if a space is used), the expression must be enclosed in single quotes.
These complex patterns are called regular expressions and we will spend quite a bit of time in this
course learning how to use this powerful way of describing strings.
1.7.5 wc
wc is used to count characters, words and lines in a file:
$ wc /usr/share/dict/words
479828 479828 4953680 /usr/share/dict/words
$ wc -l /usr/share/dict/words
479828 /usr/share/dict/words
$ wc -c /user/dict/words
4953680 /usr/share/dict/words
$
Here we print the listing of lines, words and bytes, then the lines only and then the bytes (or characters)
only for /usr/share/dict/words. Because this file only contains one word per line the number of
each is the same for this file.
1.8 Redirection
Most processes initiated by Unix commands write to the standard output (or stdout) i.e. they write to
the terminal window, and many take their input from the standard input (or stdin), i.e. they read it from
the keyboard. There is also the standard error (or stderr), where processes write their error messages,
which by default, is also to the terminal window.
$ cat
foo
foo
bar
bar
<Ctrl-D>
$
Redirection can be used to change the standard input, output and error of a program to a file instead.
1.8.2 sort
sort can be used to sort the contents of a file:
$ sort biglist
apple
banana
beef
lamb
orange
pear
$ sort < biglist > sortedlist
$ cat sortedlist
apple
banana
beef
lamb
1.8.3 pipes
Suppose we want to run some input through several programs, such as when counting the results of
grep using wc. If we use redirection, it requires the creation of temporary files.
$ touch alist
$ ls list*
list1
list2
$ ls *list
alist
biglist
filteredlist
$ ls *list*
alist
biglist
filteredlist
list1
list2
$ ls ?list
alist
$
1.10.1 man
This will produce the manual page for given program if it exists. Most standard Unix command have a
man page. These will list a description of the command and a set of options, flags and other usage
information. The manual will usually be displayed using more or less.
$ man ls
...man information...
$
If you ran the above code, you will notice that the entry is for ls(1). This means ls is in section 1 of
NAME
getopt - parse command options
...
SEE ALSO
intro(1), shell_builtins(1), sh(1), getopt(3C), attributes(5)
$ man 3 getopt
...man information for C/C++ getopt...
$
1.10.2 whatis
This produces one line descriptions of man entries containing the given keyword.
$ whatis getopt
getopt getopt (1) - parse command options
getopt getopt (3c) - get option letter from argument vector
$
1.11.1 ls
Using the -l flag for ls, we can generate a long listing of a file or directory:
$ ls -l
total 5120
-rw-r--r-- 1 bgat5227 linuxusers 35 Mar 3 12:07 biglist
drwxr-xr-x 3 bgat5227 linuxusers 0 Mar 3 09:16 Downloads
u Owner
g Group
o Other (world)
a All
+ Add permission
- Remove permission
= Set permissions
r Read
It is used as follows:
$ ls -l biglist
-rw-r--r-- 1 bgat5227 linuxusers 35 Mar 3 12:07 biglist
$ chmod g+rwx biglist
$ ls -l biglist
-rw-rwxr-- 1 bgat5227 linuxusers 35 Mar 3 12:07 biglist
$ chmod go-rwx biglist
$ ls -l biglist
-rw------- 1 bgat5227 linuxusers 35 Mar 3 12:07 biglist
$ chmod a+r,a-w biglist
$ ls -l biglist
-r--r--r-- 1 bgat5227 linuxusers 35 Mar 3 12:07 biglist
$ cat > biglist
-bash: biglist: Permission denied
Consider the words file: /usr/share/dict/words. Use Unix commands to answer the
following questions.
1. How many lines are the words file?
2. What word immediately comes before and after the word 'compute' in the words file?
3. Output the words file in reverse alphabetical order.
4. Find all words containing 'uu'.
5. Find all words which start with 'za'.
6. Find all words which end with 'space'.
7. Save all words which end with ‘space’ to a new file called ‘space.txt’.
8. Find all words which do not contain the letter 'e'.
9. How many words do not contain the letter 'e'?
10. Find all words which do not have any vowels.
11. How many words do not have any vowels?
12. Find all the word which you can type with only the top row of the keyboard.
13. Find all words which start with and end with a vowel.
1.12 Processes
1.12.1 ps
Each process executed on the system is given a unique identifier -- a process ID, or PID for short. The
$ sleep 10 &
[1] 20746
$ ps
PID TTY TIME CMD
18116 pts/4 00:00:00 bash
20746 pts/4 00:00:00 sleep
20747 pts/4 00:00:00 ps
$
Notice, there are three of your processes running (from this shell window). One of them is the shell
itself (bash), another is the ps program itself and the third is the sleep command.
1.12.2 bg and fg
A currently running process can be stopped without destroying it by using pressing <Ctrl-Z>. This
sends the process to sleep and prints the jobspec to screen. bg can then be used to start the process
again in the background. It will then run as if it had been run from the command line using the &
command. Using <Ctrl-Z> is a good trick when you forgot to put an ampersand on the end of your
command line. fg can be used to run the process in the foreground.
Here is an example of these tricks in action:
$ sleep 30
<Ctrl-Z>
[1]+ Stopped sleep 30
$ bg
[1]+ sleep 30 &
$ fg 1
sleep 30
1.12.3 jobs
This is used to list the current sleeping and backgrounded jobs:
$ sleep 30 &
[1] 21119
$ sleep 30 &
[2] 21120
$ sleep 30
<Ctrl-Z>
[3]+ Stopped sleep 30
$ jobs
[1] Running sleep 30 &
[2]- Running sleep 30 &
[3]+ Stopped sleep 30
$
1.12.4 kill
This is used to send signals to programs to stop, halt or terminate them. It takes a PID or jobspec
(preceded by a %). <Ctrl-C> is the equivalent to killing on a running process.
$ sleep 30
<Ctrl-C>
$ sleep 30 &
[1] 21158
$ jobs
[1]+ Running sleep 30 &
$ kill %1
$ jobs
[1]+ Terminated sleep 30
1.13.1 exit
This ends the current interactive shell session and so causes you to be logged out. If you still have
processes running, it will hang there until the processes have finished.
1.13.2 passwd
This allows you to change your password (note the missing ‘or’ in the command name). passwd will
first ask for the current password, and then ask you twice for the new one (to make sure you don’t
mistype it). If you get the original password wrong, it won’t change the password to the new one. It
doesn’t do this check until after you have given it a new password:
$ passwd
Old password:
New password:
Re-enter new password:
passwd: Incorrect Password.
In this case, the password has not been changed. This catches people out all of the time.
Also, the password program can be rather choosy about passwords. Please make sure that your
password isn’t easy to guess (far too many people use “password” or “password1” or their birthday)
1.13.4 tar
gzip is designed to compress a single file, so how do you compress and transfer multiple files around
the system?
The tar archiving program collates many files and directories into a single file. The name comes from
“tape archive” because these archives were often used to store lots of old files on a tape for the long-
term, in case of a need to recover to an old state. The c flag specifies create an archive file, the x flag
specifies extract an archive and the t flag specifies list the contents of an archive without extracting
files. The v flag specifies verbose output and the f flag indicates that the following argument is the
output file.
The z flag can be added to use gzip compression and decompression, which is the same as running
gzip/gunzip after/before running the tar command.
1.15.1 echo
The echo command writes its arguments to standard output and can therefore be used to display the
contents of variables. It will repeat to standard output whatever followed it on the command line.
Environment and shell variables can be accessed by using the $ symbol before their name.
$ echo $USER
bgat5227
$
1.16 Acknowledgements
Thanks to James Gorman for compiling the first version of these lab notes. They are largely derived
from the notes written by M Stonebank from the University of Surrey. Material was also taken from
the University of Utah’s Unix command summary at http://www.math. utah.edu/computing/unix/unix-
commands.html. James Curran and Tara Murphy created the previous version of the notes used in
INFO1903 until 2017. Bob Kummerfeld and Jonathan Du produced the 2018 version. The document
was improved by Kelly Stewart and Tyson Thomas in 2019, and further improved by Bob Kummerfeld
in 2020.