Lab Wk03 Exercises - Linux Command Line
Lab Wk03 Exercises - Linux Command Line
Required Reading
Java Foundations Chapter 2 Data and Expressions
Chapter 3 Sections 3.1 to 3.5
Chapter 4 Section 4.8 The For Statement
Upon completion of the lab exercises, students should be able to write simple programs
that use:
String Class for manipulating strings
Scanner Class for reading user input
Math Class methods for computing Power and Square Root
Random Class for generating random numbers in a specified range
One of the powerful capabilities of Unix is the command shell. It should be no surprise that there
are choices here too. The two most common shells are bash (the default shell in CSIL) and tcsh.
Dont like bash? You can change to tcsh with the chsh (change shell) command.
The remainder of this demo will assume the CSIL Ubuntu defaults. The examples are from the
account skristja, so you will not see the exact same output.
Unlike Windows, in Unix pretty much everything is case-sensitive. Check for this when a command
does not work as you think it should.
When you are using the command line, file and directory names with spaces are awkward to use.
Avoid them if possible.
NAME
man - an interface to the on-line reference manuals
SYNOPSIS
man [-C file] [-d] [-D] [--warnings[=warnings]] [-R
1
Linux is a particular variant of Unix. Ubuntu is a particular distribution of Linux.
Instructor: Scott Kristjanson Wk03
TAs: Yu Yang, Megan OConnor
3
Cmpt 125/126 Lab Exercises wk03: Linux Command Line Sept 16th 2013
DESCRIPTION
man is the system's manual pager. Each page argument
given to man is normally the name of a program,
utility or function. The manual page associated
with each of these arguments is then found and dis
played. A section, if provided, will direct man to
look only in that section of the manual. The
default action is to search in all of the available
sections, following a pre-defined order and to show
only the first page found, even if page exists in
several sections
... followed by a complete description of how to use the man command ...
This looks pretty intimidating, but you just have to know how to read it. Each line starting with man
is one form of the command. Lets take one of the lines:
man -f [whatis options] page ...
There is a command line flag -f, which will affect the way the man command behaves. Down in
the description of the man command, you find
Main modes of operation
-f, --whatis
Equivalent to whatis. Display a short description from the manual
Page, if available. See whatis(1) for details.
When you see text in square brackets, as [whatis options], the square brackets indicate an
optional parameter. You can add options appropriate to the whatis command. (What might those
be? Try man whatis.) And then you must supply a page. Down in the description of the man
command, you find
Each page argument given to man is normally the name of a program,
utility or function. The manual page associated with each of these
arguments is then found and displayed.
The apropos (apropos of ) command (an alias for man -k) is useful when youre not sure what
youre looking for. For example, you want to know how to list the contents of a directory, but dont
Instructor: Scott Kristjanson Wk03
TAs: Yu Yang, Megan OConnor
4
Cmpt 125/126 Lab Exercises wk03: Linux Command Line Sept 16th 2013
Where Am I?
To make sure we all start in the same place, execute the cd command:
skristja@asb9838n-a07:~$ cd
The cd (change directory) command, with no arguments, will place you in your home directory.
(Here in CSIL, thats the local home directory for the workstation.)
The pwd (print working directory) command will print the path to the current directory:
skristja@asb9838n-a07:~$ pwd
/home/skristja
Of course, you should see your user id, not skristja.
Whats Here?
The ls (list) command will list the files and subdirectories in the current directory (the set of files you see
may not be the same as shown here):
skristja@asb9838n-a07:~$ ls
android-sdk Documents Music sfuhome
C:\nppdf32Log\debuglog.txt Downloads Pictures Templates
Desktop examples.desktop Public Videos
Unix, like Windows and OS X, has hidden files and directories that hold configuration and state
information used by the operating system and various programs. To see these, add -a to the
command line:
2
The menu at the top left of the screen, under the mouse head icon.
skristja@asb9838n-a07:~$ ls -a
. Documents .local Templates
.. Downloads .mozilla Videos
android-sdk examples.desktop Music .viminfo
.bash_logout .gconf Pictures .Xauthority
.bashrc .gnome2 .profile .Xdefaults
.cache .gnome2_private Public .xscreensaver
.config .gstreamer-0.10 .pulse .xsession-errors
.dbus .gvfs .pulse-cookie
Desktop .ICEauthority sfuhome
Yes, there are lots of them. For example, the .config directory is used by the Xfce window
manager to store configuration information. The file .bashrc is executed by the bash shell as it
starts up. This is the place to put your own custom command aliases or remove default aliases
that you dont like.
How can I tell which entries are files, and which are directories? On many systems, ls will
produce color-coded output, but if not, you can use the -F flag:
skristja@asb9838n-a07:~$ ls -F
android-sdk@ Downloads/ Pictures/ Templates/
Desktop/ examples.desktop Public/ Videos/
Documents/ Music/ sfuhome/
Directories have a / added to the end. Executable files have an * tacked on the end. Plain old
files have nothing added. Other characters are used to indicate other file types.
If you give a file or directory name, ls will restrict itself to just that file or directory. Suppose that I
want some details for sfuhome. I can add the -l and -d flags to my ls command, with the directory
name, and get:
skristja@asb9838n-a07:~$ ls -ld sfuhome
drwx--s--x 11 skristja users 0 Sep 14 13:03 sfuhome
What does this output mean? Heres a quick description of the fields that are interesting in an
introduction:
drwx--s--x are the file permissions. These permissions show that sfuhome is a directory
(the leading d); that I can read (browse), write (create), and execute (access) the directory
(the next three characters, rwx); and that others can execute files in my sfuhome directory
only if they know the file name (the characters --x mean that others can access the files
but not browse them). The chmod (change mode) command is used to manipulate file
permissions. For optional reading on Linux permission bits, check out
http://danielmiessler.com/study/unixlinux_permissions/
skristja is the owner of the file.
0 is the size in bytes. (Recall that sfuhome is mounted from a file server in ITS; the mount
itself occupies no space.)
Sept 14 13:03 is the time the directory was last modified.
Notice that many Unix commands use single-letter options, and you can combine those options
with a single -. Try ls -alF.
Suppose you just want to see the files with extension .txt? Unix command shells support
wildcard characters in file and directory names. The character * matches any string; ? matches
any single character.
Instructor: Scott Kristjanson Wk03
TAs: Yu Yang, Megan OConnor
6
Cmpt 125/126 Lab Exercises wk03: Linux Command Line Sept 16th 2013
skristja@asb9838n-a07:~$ ls *.txt
C:nppdf32Logdebuglog.txt
skristja@asb9838n-a07:~$ ls -d ?o*
Documents Downloads
In the second ls command, I asked for a listing of any name that has o as the second character.
The directories Documents and Downloads matched.
Remember, in a Unix command shell the character ~ in a file name is the abbreviation for your
home directory. You can, of course, change the prompt to anything you like. Consult the
documentation for bash.
3
This is an artifact of sharing your ITS home directory between unix and Windows using a common file
system standard called CIFS. CIFS has difificulty with unix file permissions. Technical staff are trying to work
around this; at present the behaviour seems to be inconsistent from one workstation to the next.
Instructor: Scott Kristjanson Wk03
TAs: Yu Yang, Megan OConnor
8
Cmpt 125/126 Lab Exercises wk03: Linux Command Line Sept 16th 2013
himom.txt
If you like the opportunity for a second thought, its easy to get it back:
skristja@asb9838n-a07:~/sfuhome/Demo$ alias rm='rm -i'
skristja@asb9838n-a07:~/sfuhome/Demo$ alias rm
alias rm='rm -i'
The proper place to put the unalias command is in your .bashrc file, where it will take effect
automatically. This is also a good place to add aliases you like or modify your default search path.
The search path is the set of directories that Unix searches when looking for executable files.
What about deleting a directory? Lets move up out of the Demo directory and delete it:
skristja@asb9838n-a07:~/sfuhome/Demo$ cd ..
skristja@asb9838n-a07:~/sfuhome$ rm Demo
rm: cannot remove `Demo': Is a directory
Hmmm . . . not very successful. Some of you may know that there is another command, rmdir,
specifically for removing directories:
skristja@asb9838n-a07:~/sfuhome$ rmdir Demo
rmdir: failed to remove `Demo': Directory not empty
We could remove Demo/himom.txt and then remove the Demo directory, but thats not really
necessary:
skristja@asb9838n-a07:~/sfuhome$ rm -r Demo
rm: descend into directory `Demo'? y
rm: remove regular file `Demo/himom.txt'? y
rm: remove directory `Demo'? y
skristja@asb9838n-a07:~/sfuhome$ ls
bin CMPT 150 personal $RECYCLE.BIN
cmpt125 desktop.ini pub_html
The -r flag (recursive) tells the rm command that you intend to remove the directory and its
contents, recursively. The interactive alias makes this more than a little tedious. Use this command
with care4 if you have removed the interactive alias for rm!
The -r flag can be used in many commands, with the same meaning: Perform the action for the
directory and all its contents, recursively.
In general, Unix command line applications take the attitude that you know what you are doing.
They do not ask Are you sure?, they just do what you request. Think before you hit the return key.
4
Some of you may be aware that the name of one of the universitys mail servers is rm-rstar. Now you can
appreciate the joke. Never type rm -r * without careful thought to the consequences!
Instructor: Scott Kristjanson Wk03
TAs: Yu Yang, Megan OConnor
9
Cmpt 125/126 Lab Exercises wk03: Linux Command Line Sept 16th 2013
himom.txt
The cp (copy) command will copy a file:
skristja@asb9838n-a07:~/sfuhome/Demo$ cp himom.txt another.txt
skristja@asb9838n-a07:~/sfuhome/Demo$ ls
another.txt himom.txt
You can copy entire directory trees with a single command using the -r flag:
skristja@asb9838n-a07:~/sfuhome/Demo$ cd ..
skristja@asb9838n-a07:~/sfuhome$ cp -r Demo Demo2
skristja@asb9838n-a07:~/sfuhome$ ls
bin CMPT 150 Demo2 personal $RECYCLE.BIN
cmpt125 Demo desktop.ini pub_html
skristja@asb9838n-a07:~/sfuhome$ ls Demo
another.txt himom.txt
skristja@asb9838n-a07:~/sfuhome$ ls Demo2
another.txt himom.txt
The mv command (move) will move a file or directory from one place to another. To rename a file,
simply move it to the new name:
skristja@asb9838n-a07:~/sfuhome$ mv Demo/himom.txt Demo2/byemom.txt
skristja@asb9838n-a07:~/sfuhome$ ls Demo
another.txt
skristja@asb9838n-a07:~/sfuhome$ ls Demo2
another.txt byemom.txt himom.txt
Moving a directory works the same way:
skristja@asb9838n-a07:~/sfuhome$ mv Demo2 NewDemo
skristja@asb9838n-a07:~/sfuhome$ ls
bin CMPT 150 desktop.ini personal $RECYCLE.BIN
cmpt125 Demo NewDemo pub_html
skristja@asb9838n-a07:~/sfuhome$ ls NewDemo
another.txt byemom.txt himom.txt
As mentioned before, Unix assumes you know what youre doing. If you move or copy a file, and a
file of the same name already exists, it will be overwritten without complaint:
skristja@asb9838n-a07:~/sfuhome$ ls Demo
another.txt
skristja@asb9838n-a07:~/sfuhome$ ls NewDemo
another.txt byemom.txt himom.txt
skristja@asb9838n-a07:~/sfuhome$ mv NewDemo/himom.txt Demo/another.txt
skristja@asb9838n-a07:~/sfuhome$ ls Demo NewDemo
Demo:
another.txt
NewDemo:
another.txt byemom.txt
Be careful! If you would rather have a safety net, you can use the -i option for mv and cp5:
skristja@asb9838n-a07:~/sfuhome$ ls Demo
another.txt
skristja@asb9838n-a07:~/sfuhome$ ls NewDemo
5
The current default aliases in CSIL provide cp -i but not mv -i.
Instructor: Scott Kristjanson Wk03
TAs: Yu Yang, Megan OConnor
10
Cmpt 125/126 Lab Exercises wk03: Linux Command Line Sept 16th 2013
another.txt byemom.txt
skristja@asb9838n-a07:~/sfuhome$ mv -i Demo/another.txt NewDemo
mv: overwrite `NewDemo/another.txt'? n
skristja@asb9838n-a07:~/sfuhome$ ls Demo
another.txt
skristja@asb9838n-a07:~/sfuhome$ ls NewDemo
another.txt byemom.txt
As you can see, typing n (no) to the prompt aborts the move. If you like this style, create aliases.
Notice that the mv command specifies a specific file to move (Demo/another.txt) and only a
directory (NewDemo) for the target. This says move the file to the target directory; but do not
change the file name.
Recall that I mentioned that file and directory names with spaces are awkward. If you forget, or
you transfer a file from Windows and the name contains spaces, you must use quotes (single or
double) around the name:
skristja@asb9838n-a07:~/sfuhome$ cd Demo
skristja@asb9838n-a07:~/sfuhome/Demo$ touch "Name With Spaces"
skristja@asb9838n-a07:~/sfuhome/Demo$ ls
another.txt Name With Spaces
skristja@asb9838n-a07:~/sfuhome/Demo$ rm Name With Spaces
rm: cannot remove `Name': No such file or directory
rm: cannot remove `With': No such file or directory
rm: cannot remove `Spaces': No such file or directory
skristja@asb9838n-a07:~/sfuhome/Demo$ rm "Name With Spaces"
rm: remove regular empty file `Name With Spaces'? y
skristja@asb9838n-a07:~/sfuhome/Demo$ ls
another.txt
Unix command shells assume that spaces separate parameters6. Here, the shell interprets Name
With Spaces as three separate file names, and complains that it cant find any of them.
6
So does the Windows command shell cmd.exe, but most people never use cmd.exe because it has so little
power. If you want to learn a decent shell for Windows, have a look at PowerShell, included in Windows 7.
Instructor: Scott Kristjanson Wk03
TAs: Yu Yang, Megan OConnor
11
Cmpt 125/126 Lab Exercises wk03: Linux Command Line Sept 16th 2013
command does not rely on the file name extension. It looks at the content of the file77 and makes
its best guess, but it can be fooled.
Text files can be dumped to the terminal with the cat command, but usually you want a bit more
control. The best pager is a command called less (a pun at the expense of the less capable
pager program called more).
skristja@asb9838n-a07:~/sfuhome$ less Demo/another.txt
Hi, Mom!
Demo/himom.txt (END)
Type q to exit the pager.
For serious file manipulation, you will want to use an editor. The two historical command line ascii
text editors are vim and emacs. You will want to experiment with them. They have radically
different approaches to editing, and the choice between them is entirely a matter of personal taste.
The learning curve is steep for both of them, but they are very powerful when it comes to creating
and editing program text8. There are many other editors available ask friends, do some Internet
searching, find something that works for you. Eclipse has a built-in editor with considerable
knowledge of Java syntax and formatting.
To view PDF and Postscript, use the evince viewer. Adobe acroread is also available for PDF
files. An easy way to read PDF in Ubuntu is to use the graphical file browser, and simply double
click on the PDF file you want to open.
7
More accurately, file looks at the initial bytes of a file.
8
To take full advantage of the power of vi or emacs, and many other Unix command line programs, you will
want to learn regular expressions, a powerful way of expressing text patterns. man 7 regex will get you the
man page for regular expressions. For a gentler introduction, search regular expression tutorial in your
favourite search engine.
Instructor: Scott Kristjanson Wk03
TAs: Yu Yang, Megan OConnor
12
Cmpt 125/126 Lab Exercises wk03: Linux Command Line Sept 16th 2013
another.txt HelloWorld.java
If you have deleted the HelloWorld project, you can download HelloWorld.java from the
url http://www.cs.sfu.ca/CourseCentral/125/skristja/Demos/CmdLine/HelloWorld.java
Place it in the Demo directory.
To compile a Java program, run the Java compiler, javac:
skristja@asb9838n-a07:~/sfuhome/Demo$ ls
another.txt HelloWorld.java
skristja@asb9838n-a07:~/sfuhome/Demo$ javac HelloWorld.java
skristja@asb9838n-a07:~/sfuhome/Demo$ ls
another.txt HelloWorld.class HelloWorld.java
skristja@asb9838n-a07:~/sfuhome/Demo$ file HelloWorld.class
HelloWorld.class: compiled Java class data, version 50.0 (Java 1.6)
Running the compiler produces the file HelloWorld.class, which is Java bytecode. The
compiler requires that you specify the .java extension on the source file.
To run the program, you run the Java interpreter java with the class file as the parameter:
skristja@asb9838n-a07:~/sfuhome/Demo$ java HelloWorld
Hello, World!
Do not specify the .class extension! The Java interpreter will complain. (It tries to interpret the . in
terms of Javas notion of how derived class files should be stored in the file system.)
During the semester, you will be asked to submit your Java source files as your solution to an
assignment. As explained above, you can find the source files within the project directory in the
Eclipse workspace.
Scripts
One of the great strengths of using the Linux command line interface is that it provides you with
the ability to automate tasks. To do so, your can create bash scripts which will perform customized
functions for you. We will discuss that in an upcoming tutorial.
I Want More!
If this is already more command line Unix than you wanted to know, you can stop now. This
tutorial contains enough to allow you to do the work required for the course. If youre looking for
more information, theres lots of it out there. Consult the Unix documentation links at the bottom of
the Resources page on the course web site.
object string s1 (and you are not passing any parameters, as there is an
empty list of parameters, as indicated by (). What does the method return?
6. Explore what happens when you assign one String to Another. Add the
following code at the end of your existing main program:
System.out.println("s1 is \"" + s1 + "\"");
System.out.println("s3 is \"" + s3 + "\"");
System.out.println("Assigning s3 = s1;");
s3 = s1;
System.out.println("s1 is \"" + s1 + "\"");
System.out.println("s3 is \"" + s3 + "\"");
Give it a try but remember to hit <escape> to get out of these modes. Then
type :q! to abort any changes that you have made.
i. Some commands take immediate affect but leave you in command mode so
you there is no need to hit <escape> to return to command mode. These
commands include:
x - delete current character
dw delete to end of current word
dd Delete current line
r - replace current character
. repeat the last command
For these commands, you can optionally enter a number before the
command, then the command will be repeated that many times. For
example, this command will delete the next 10 lines:
10dd
j. You may want to cut and paste code. You can cut the code using the vim
dd command. Then move the cursor to where you want to paste the code,
and type the letter p to paste the code after the current line.
k. Command line editing is not for the faint of heart, but learning it is worth the
trouble. Until you have mastered vim, you can always use a graphical editor
when you are sitting at a CSIL computer or at your home PC, but your
choices are limited to command line text based editors like vim when you
login to CSIL remotely. Fortunately, VIM provides an extensive help menu.
To view the vim help menu, use the help command:
:help
l. Later, you can save your changes using the write and quit command: :wq
For now, discard all your changes by typing :q!
:q!
p. If you want to use CSIL remotely from home, you will need to get familiar
with vim so you can edit your files remotely. You will use ssh to login
remotely and scp to transfer files to a CSIL machine. If you prefer, you can
always edit your files at home using a graphical editor and then use scp to
copy the new version back to your CSIL machine so you can test it. The
Course Webpage has links describing how to access CSIL remotely. We will
look into that in more detail in another lab.
System.out.println();
}
}
}
c. Compile and run the Lab03For program to watch a Java for loop in action.
skristja@asb9838n-a07:~/sfuhome/cmpt125/lab03for$ javac Lab03For.java
skristja@asb9838n-a07:~/sfuhome/cmpt125/lab03for$ java Lab03For
*
**
***
****
*****
******
*******
********
*********
**********
first. Then test it inside the main method in the Lab03For application from the
previous question. Insert this code in the main method body after the } following
the body of the existing for loop.
for (int i = 1; i<= 2; i++)
{
for (int j = 1; j<=4; j=j+1)
{
System.out.println("i is:" + i + " and j is " + j);
}
System.out.println( );
}
9. Explore the Scanner Class
a. The Scanner methods allow us to interact with the user. The Scanner
class has to be imported. A Scanner object needs to be created since we
need to instantiate a Scanner object instance to read from a specific input
stream such as System.out.
b. Create a new project called Lab03Scanner and create Lab03Scanner
Class with a public static void main() method as before.
c. Within the Java file, you will need to insert the following line to import the
java.util.Scanner package. Insert it after the block comment and before the
class definition.
import java.util.Scanner;
d. We are going to re-create the GasMileage example from Listing 2.9 of the
text. To compute mileage, in miles/gallon, one needs to take the number
miles travelled and divide by the number of gallons of gas used to get there.
e. To start, we will need an integer variable to represent the number of miles
that we have driven. Define an int at the start of your main method body
called miles.
f. Next we need to know how many gallons of gas our car used. This is not
likely to be a whole number so it should be represented as a floating point
number. Define a second variable called gallons which is a double.
g. Finally, the computed mileage will be a fractional value so also needs to be
stored in a double. Define it as the third local variable in your method.
h. In this program, we want to use the Scanner class to allow us to receive
input from the user. Declare a Scanner object called scan and instantiate it
by called the Scanner construction method and specifying that the input
stream is the System.in object:
Scanner scan = new Scanner (System.in);
i. Now you use the scan object to request an int value from the user about
how far they travelled. Use the nextInt method to read the input stream
and return an integer value:
a. Do some calculations using various math methods. Since its methods are
static, you do not create an object of the class Math to use the method but
instead you qualify the method with the class name using the dot notation.
See section 3.5 in the textbook.
b. Create a new project called Lab03Math with a Lab03Math Class
c. In the main method, you will re-create the Quadratic example from Listing
3.3 in the textbook to compute the roots of a Quadratic equation using
methods from the Math class. Start by including the following statements to
declare your three integer quadratic coefficients a, b and c at the start of the
main method body.
int a, b, c; // ax^2 + bx + c
d. Next, you need to have two doubles for storing the computed roots:
double root1, root2;
e. As with the Scanner exercise, instantiate a Scanner object and request the
input values from the user:
Scanner scan = new Scanner (System.in);
num1 = generator.nextInt();
System.out.println ("A random integer: " + num1);
num1 = generator.nextInt();
System.out.println ("A random integer: " + num1);
num1 = generator.nextInt(10);
System.out.println ("From 0 to 9: " + num1);
num1 = generator.nextInt(10) + 1;
System.out.println ("From 1 to 10: " + num1);
num2 = generator.nextFloat();
System.out.println ("A random float (between 0-1): " + num2);