Professional Documents
Culture Documents
(Teach Yourself)
What Is UNIX?
• UNIX is a computer operating system.
• An operating system is the program that controls all the other parts of a computer system,
both the hardware and the software. It allocates the computer's resources and schedules
tasks. It allows you to make use of the facilities provided by the system. Every computer
requires an operating system.
• UNIX is a multi-user, multi-tasking operating system. Multiple users may have multiple
tasks running simultaneously. This is very different than PC operating systems.
• UNIX is a machine independent operating system. Not specific to just one type of
computer hardware. Designed from the beginning to be independent of the computer
hardware.
• UNIX is a software development environment. Was born in and designed to function
within this type of environment.
• The "UNIX" trademark, previously owned by AT&T and then deeded to UNIX Systems
Laboratories (USL), an AT&T subsidiary, passed to Novell when it acquired USL. After
a brief period of negotiations with rival Unix vendors Sun Microsystems, Santa Cruz
Operation, International Business Machines, and Hewlett-Packard, Novell granted
exclusive licensing rights to the UNIX trademark to X/Open Co. Ltd., an Open Systems
industry standards branding agent based in the United Kingdom.
History of UNIX
• 1969: Developed at AT&T Bell Labs in Murray Hill, New Jersey, one of the largest
research facilities in the world. Created in an environment when most computer jobs were
fed into a batch system.
UNIX Philosophy
• Make each program do one thing well. Reusable software tools: 1 tool = 1 function
• Expect the output of every program to become the input of another, yet unknown,
program to combine simple tools to perform complex tasks
• Prototyping: get something small working as soon as possible and modify it
incrementally until it is finished
• Use terse commands and messages: reduces typing and screen output
Why UNIX?
• Hardware independence
o operating system code is written in C language rather than a specific assembly
language
o operating system software can be easily moved from one hardware system to
another
o UNIX applications can be easily moved to other UNIX machines. Porting is
usually as simple as transfer of the source and a recompile
• Productive environment for software development
o rich set of tools
o versatile command language
UNIX Components
• Kernel
o The core of the UNIX system. Loaded at system start up (boot). Memory-resident
control program.
o Manages the entire resources of the system, presenting them to you and every
other user as a coherent system. Provides service to user applications such as
device management, process scheduling, etc.
o Example functions performed by the kernel are:
managing the machine's memory and allocating it to each process.
scheduling the work done by the CPU so that the work of each user is
carried out as efficiently as is possible.
accomplishing the transfer of data from one part of the machine to another
interpreting and executing instructions from the shell
enforcing file access permissions
o You do not need to know anything about the kernel in order to use a UNIX
system. These details are provided for your information only.
• Shell
o Whenever you login to a Unix system you are placed in a shell program. The
shell's prompt is usually visible at the cursor's position on your screen. To get
your work done, you enter commands at this prompt.
o The shell is a command interpreter; it takes each command and passes it to the
operating system kernel to be acted upon. It then displays the results of this
operation on your screen.
o Several shells are usually available on any UNIX system, each with its own
strengths and weaknesses.
o Different users may use different shells. Initially, your system adminstrator will
supply a default shell, which can be overridden or changed. The most commonly
available shells are:
Bourne shell (sh)
C shell (csh)
Korn shell (ksh)
TC Shell (tcsh)
Bourne Again Shell (bash)
o Each shell also includes its own programming language. Command files, called
"shell scripts" are used to accomplish a series of tasks.
• Utilities
o UNIX provides several hundred utility programs, often referred to as commands.
o Accomplish universal functions
o Many UNIX systems will display a login banner or "message of the day". Make a
habit of reading this since it may contain important information about the system.
o Other UNIX systems will automatically configure your environment and open one
or more windows for you to do work in.
o You should see a prompt - usually a percent sign (%) or dollar sign ($). This is
called the "shell prompt" (the shell is discussed in detail later). It indicates that the
system is ready to accept commands from you.
U If your login attempt was unsuccessful, there are several possible reasons:
• Example
•
• login: kellyk
• kellyk's Password:
• ************************************************************
• * Welcome to the Maui High Performance Computing Center
• ************************************************************
• *
• * Aloha no! (Greetings)
• *
• * System maintenance is scheduled today from 2:00
• * until 4:00 pm HST
• *
• * Mahalo nui loa (Thank you very much)
• *
• ************************************************************
•
• %
• Options
1. Modify the way that a command works
2. Usually consist of a hyphen followed by a single letter
3. Some commands accept multiple options which can usually be grouped together
after a single hyphen
4. A small number of commands require each option to be given separately
5. Should be separated from the command name by a space
• Arguments
1. Most commands are used together with one or more arguments
2. Some commands assume a default argument if none is supplied
3. Arguments are optional for some commands and required by others
4. In most cases, multiple arguments should be separated from each other by a
space. They should be separated from the command name and/or options by a
space also.
• Examples
1. To use a command with no argument: the "date" command displays the current
time and date.
date
2. To use a command with a single argument: the "cd" command changes to the
directory of its argument, newdir
cd newdir
8. To use a command with several arguments: the cat command takes the names of
three files as arguments. It prints file1 followed by file2 and then file3 on the
screen.
9. To use a command with multiple options and default argument: the ls command
provides a long (l) listing of all (a) files and also shows the file size (s). Because
no argument is specified, the default argument (current directory) will be used.
ls -als
• Multiple commands can be entered on one line if you separate each with a semicolon. For
example: this command line contains two commands. The first, cd newdir changes the
current directory to the directory newdir. The second, ls -l produces a long listing of the
contents of the newdir directory.
cd newdir ; ls -l
• Commands can continue beyond one line by using a backslash (\) character. For example:
this command copies the file called recipe from kelly's home directory to the current
directory and renames it kelly.recipe. It then sends this file to the printer ps3 with the
request that 6 copies be printed.
•
• cp /users/kelly/recipe kelly.recipe ; \
• lpr -Pps3 #6m kelly.recipe
Special Characters
• The UNIX shell interprets a number of characters in special ways. These characters are
most often used with UNIX commands - as arguments and for other means. The
following list contains most of UNIX's special characters
•
• NEWLINE - initiates command execution
• ; - separates commands on same line
• ( ) - groups commands or identifies a function
• Examples
1. Use the * character in file names to match any number of characters. The
following command:
ls *.txt
doctxt txt.memo
2. Use the ? character in file names to match any single character. The following
command:
ls ???.txt
chap1.txt doctxt
ls chapter[1-3].txt
chap1.txt chapter4.txt
• Other uses for special characters and examples will be discussed later.
Note that what you type will not appear on the screen for security reasons. For example:
passwd
Old password: - enter your current password
New password: - enter your new password
Retype new password: - re-enter your new password
Don't
Do
Getting Information
• The "man" command
o The "man" command man gives you access to an on-line manual which
potentially contains a complete description of every command available on the
system. In practice, the manual usually contains a subset of all commands.
o man can also provide you with one line descriptions of commands which match a
specified keyword
man cp
--More--23% at the bottom left of the screen means that only 23% of
the man page is displayed. Press the space bar to display more of it or type
q to quit.
man 8 telnetd
whatis more
The simplest way to accomplish the logout is to just issue the logout command
again. Your suspended/background jobs will be terminated and you will be logged
off the system.
2. If you see the message Not login shell it means you are working in
another "shell" that has been started from within your "login shell" (shells will be
discussed later).
To logout, issue the exit command and then try to logout again.
Introduction to UNIX
Getting Started Exercises
Logging On To The System
The details of logging in to a UNIX computer will differ from system to system. The steps covered here
are specific for the MHPCC classroom.
1. The instructor will assign every student a unique userid and password. Make sure you know
yours before proceeding. The instructor will also show you how to setup your terminal for
logging on.
Parimal Sudas Page 12
2. After your computer terminal is ready for logging on, review the screen and look for a place to
type in your userid and password.
3. Type in your userid, making sure that you distinguish between uppercase and lowercase letters
as required. Press the return key when finished.
4. Type in your password, also making sure that you distinguish between uppercase and lowercase
letters as required. It will not appear as you type for security reasons. Press the return key when
finished.
5. If you are unsuccessful at logging in, the system will give you another try. Keep trying until you
succeed. If you don't succeed after 5 tries, call the instructor.
6. After you have successfully logged in, the system will automatically create your initial
environment including a clock and a window for entering commands.
7. Notice the window - it should ask you which type of session you want. Answer the prompt by
typing in the number which matches: Introduction to UNIX. You will then be prompted to "start
Netscape" - type y for yes.
8. After a few seconds, you should see the Introduction to UNIX window. If you do not, call the
instructor.
9. Return to the tutorial to learn about the next section before proceeding.
1. You should still have a window on your screen from the previous exercise. Select that window
by dragging the mouse pointer into the window and then clicking with the left mouse button.
The window is now ready to accept input from you.
2. Try a few simple commands which require no arguments or options:
3.
4. date - show date and time
5. whoami - show your userid
6. who - show who is logged onto the system
7. w - show who is logged onto the system
8. pwd - print the working directory's name
9. clear - clear the screen
10. Now try some commands which require arguments and/or options:
11.
12. ls -a - list all files in current directory
13. ls -al - long list of current directory
14. cat .cshrc - display contents of .cshrc file
15. mkdir dir1 - make a directory called dir1
16. cd dir1 - change directory to dir1
17. cd .. - change to parent directory
18. rmdir dir1 - remove directory dir1
19. cp .login new.login - copy the .login file to new.login
20. wc new.login - count the lines, words and
21. characters in the new.login file
22. wc -l new.login - count just the lines
23. rm new.login - remove the new.login file
24.
33. Return to the tutorial to learn about the next section before proceeding.
Special Characters
This exercise will acquaint you with the use of several of the UNIX special characters.
1. First, make sure you are in your home directory (issue the "cd" command with no arguments).
Now "cd" to this exercise's subdirectory by using the command:
2.
3. cd GetStart
4. Using the "*" wildcard character, list all of the files in this subdirectory:
5.
6. ls *
7. Using the "?" wildcard character, list all files with 3 character names:
8.
9. ls ???
10. Using square brackets and wildcard characters, try listing files several different ways:
11.
12. ls [a-c]*
13. ls [abcde]*
14. ls [a-z]*
15. ls [z]*
16. ls ??[c]*
17. ls ?[e]*
18. Using the right angle bracket ">" and the semi-colon ";", concatenate three files into a single
new file and then display it:
19.
20. cat alpha beta gamma > newfile ; cat newfile
1. Erasing the command line: At the command prompt, begin typing several characters. It doesn't
matter what you type (but don't press the Return key) because you will then erase the line by
typing CTRL-u.
2. Killing a command: Start the command sleep 300 which simply "sleeps" for 300 seconds.
After it is started, try using another UNIX command such as "ls". What happens? Kill the sleep
process by using CTRL-c, and try it again. What happens now?
3. Backspacing: At the command prompt, begin typing several characters. It doesn't matter what
you type (but don't press the Return key). After typing several characters, try using CRTL-h to
backspace. Most keyboards will allow you to backspace by using a "backspace" or "delete" key
also.
4. Screen Scrolling: Issue a command which will send lots of information to the screen: ls -R /
While the information is being displayed, use CTRL-s to stop it and then CTRL-q to restart it. Try
CTRL-s and CTRL-q a couple times. Then kill the process with CTRL-c.
5. Return to the tutorial to learn about the next section before proceeding.
1. Each student should have received an initial password from the instructor. If you are not sure of
yours, ask the instructor.
2. Think of a new password which follows the guidelines mentioned in the tutorial. Remember
what it is.
3. Change your initial password by issuing the passwd command. As your are prompted, supply
your old password and then your new password. You will be asked to type the new password
twice for confirmation. Notice that nothing appears on the screen as you type.
4. Now change your password back to the original password. Please don't forget to do this step!
5. Return to the tutorial to learn about the next section before proceeding.
Getting Information
This exercise will familiarize you with several different UNIX utilities for obtaining information about the
system.
1. Use the man command to read in depth about some common UNIX utilities:
2.
3. man ls
4. man cp
5. man rm
6. man man
14. Return to the tutorial to learn about the next section before proceeding.
5. This will cause your window to disappear. In other UNIX systems, without a windows
environment, these same commands would terminate your entire session.
File Types
The UNIX filesystem contains several different types of files:
• Ordinary Files
o Used to store your information, such as some text you have written or an image
you have drawn. This is the type of file that you usually work with.
o Always located within/under a directory file
o Do not contain other files
• Directories
o Branching points in the hierarchical tree
o Used to organize groups of files
o May contain ordinary files, special files or other directories
o Never contain "real" information which you would work with (such as text).
Basically, just used for organizing files.
o All files are descendants of the root directory, ( named / ) located at the top of the
tree.
• Special Files
o Used to represent a real physical device such as a printer, tape drive or terminal,
used for Input/Ouput (I/O) operations
o Unix considers any device attached to the system to be a file - including your
terminal:
By default, a command treats your terminal as the standard input file
(stdin) from which to read its input
Your terminal is also treated as the standard output file (stdout) to which a
command's output is sent
Stdin and stdout will be discussed in more detail later
o Two types of I/O: character and block
o Usually only found under directories named /dev
• Pipes
o UNIX allows you to link commands together using a pipe. The pipe acts a
temporary file which only exists to hold data from one command until it is read
by another
o For example, to pipe the output from one command into another command:
o
o who | wc -l
File Names
• UNIX permits file names to use most characters, but avoid spaces, tabs and characters
that have a special meaning to the shell, such as:
•
• & ; ( ) | ? \ ' " ` [ ] { } < > $ - ! /
• Case Sensitivity: uppercase and lowercase are not the same! These are three different
files:
•
• NOVEMBER November november
• Hidden Files: have names that begin with a dot (.) For example:
•
• .cshrc .login .mailrc .mwmrc
• Uniqueness: as children in a family, no two files with the same parent directory can have
the same name. Files located in separate directories can have identical names.
• Reserved Filenames:
•
• / - the root directory (slash)
• . - current directory (period)
• .. - parent directory (double period)
• ~ - your home directory (tilde)
• Relative Pathname: tells how to reach a file from the directory you are currently in
( current or working directory); never begins with / (slash). For example:
•
• training/sample.f
• ../bin
• ~/projects/report.001
• For example, if your current directory is /usr/home/johnson and you wanted to change to
the directory /usr/home/quattro, you could use either of these commands:
•
• cd ../quattro - relative pathname
• cd /usr/home/quattro - absolute pathname
• ls - lists files
•
• ls - show contents of working directory
• ls file - list file, if it exists in working directory
• ls dir - show contents of the directory dir
• ls -a - shows all your files, including hidden ones
• ls -al - give detailed listing of contents
• ls -F - mark directories with "/" and executable
• files with "*"
• ls *.doc - show all files with suffix ".doc"
• more - browses/displays files one screen at a time. Use h for help, spacebar to page, b for
back, q to quit, /string to search for string
Parimal Sudas Page 19
•
• more sample.f
• pg - browses/displays files one screen at a time. Similar to the more utility in function but
has different commands and options. See the man page for details.
•
• pg sample.f
• less - similar to more, but with more features. Not available on every system.
•
• less sample.f
• cat - dumps the entire file to the screen without paging. This command is more useful for
concatenating (hence the name "cat") files together than it is for reading files.
•
• cat myprog.c - diplays entire file
• cat -b myprog.c - shows line numbers
• cat file1 file2 > file3 - adds file1 and file2 to make
• file3
• cp - copies files. Will overwrite unless otherwise specified. Must also have write
permission in the destination directory.
•
• cp sample.f sample2.f - copies sample.f to sample2.f
• cp -R dir1 dir2 - copies contents of directory
• dir1 to dir2
• cp -i file.1 file.new - prompts if file.new will be
• overwritten
• cp *.txt chapt1 - copies all files with .txt
• suffix to directory chapt1
• mv - moves files. Will overwrite unless otherwise specified. Must also have write
permission in the destination directory.
•
• mv sample.f sample2.f - moves sample.f to sample2.f
• mv dir1 newdir/dir2 - moves contents of directory
• dir1 to newdir/dir2
• mv -i file.1 file.new - prompts if file.new will be
• overwritten
• mv *.txt chapt1 - moves all files with .txt
• suffix to directory chapt1
For example:
The pathname defines the directory to start from. Each subdirectory of this directory will
be searched.
You can define the filename using wildcards. If these are used, the filename must be
placed in 'quotes'.
• diff - comparing two files or directories. Indicates which lines need be added (a), deleted
(d) or changed (c). Lines in file1 are identified with a (<) symbol: lines in file2 with a (>)
symbol
•
• diff file1 file2 - compares file1 to file2
• diff -iw file1 file2 - compares two files ignoring
• letter case and spaces
• diff dir1 dir2 - compares two directories
• showing files which are
• unique to each and also,
• line by line differences
• between any files in common.
Using the diff command: diff file1 file2 Yields the output:
2a3,4
> Jean JRS@pollux.ucs.co
> Jim jim@frolix8
Which means that to make these files match you need to add (a) lines 3 and 4 (3,4) of
file2 (>) after line 2 in file1.
• sdiff - similar to diff, but displays each line of the two files side by side, making it easier
for you to see the differences between them
Lines that are different are shown with a | symbol. Lines unique to file1 are identified by
a < symbol; lines unique to file2 with a > symbol. Identical lines appear next to each
other. The option -w 80 is used to set the width of the output from the command to 80
characters. The default is 130 characters.
Making a link to a file or directory does not create another copy of it. It simply makes a
connection between the source and the linkname. Allows a single file to be "pointed to"
by other filenames without having to duplicate the file.
• sort - sorts files, merges files that are already sorted, and checks files to determine if they
have been sorted. The command syntax is:
•
• sort options filename
By default, lines in "filename" are sorted and displayed to the screen. If the "filename"
parameter specifies more than one file, the sort command concatenates the files and sorts
them as one file.
The sort command supports many options. See the man page for details.
• pwd - print working directory. Tells you which directory you are currently in.
•
• pwd
• cd - change to specified directory. May specify either the absolute or relative pathname.
cd with no pathname changes to your home directory.
•
• cd /usr/local - change to /usr/local
• cd doc/training - change to doc/training in current
• directory
• cd .. - change to parent directory
• cd ~/data - change to data directory in
• home directory
• cd ~joe - change to user joe's home directory
• cd - change to home directory
• rmdir - remove directory. Directories must be empty before you remove them.
•
• rmdir project1
To recursively remove nested directories, use the rm command with the -r option:
rm -r dirctory_name
• A summary of commands and utilities related to the UNIX file system appears below.
See the corresponding man pages for detailed information.
•
• awk -search for and process patterns in a file,
• cat -display, or join, files
• cd -change working directory
• chgrp -change the group that is associated with a file
• chmod -change the access mode of a file
• chown -change the owner of a file
• comm -compare sorted files
• cp -copy files
• df -display the amount of available disk space
• diff -display the differences between two files
• du -display information on disk usage
• file -display file classification
• find -find files
• fsck -check and repair a file system
• grep -search for a pattern in files
Access Permissions
• UNIX is a multi-user system. Every file and directory in your account can be protected
from or made accessible to other users by changing its access permissions. Every user has
responsibility for controlling access to their files.
• Permissions for a file or directory may be any or all of:
•
• r - read
• w - write
• x - execute = running a program
• Note: a directory must have both r and x permissions if the files it contains are to be
accessed.
• The chmod command is used to change access permissions for files which you own. The
syntax is:
•
• chmod permission_triads filename
• [who][action][permissions]
where:
Examples:
chmod +w *
- Adds write permission for user to all files in
current directory.
• File access permissions can also be changed by a numerical (octal) chmod specification.
Read permission is given the value 4, write permission the value 2 and execute
permission 1.
•
• r w x
• 4 2 1
These values are added together for any one user category:
0 = no permissions
1 = execute only
2 = write only
3 = write and execute (1+2)
4 = read only
5 = read and execute (4+1)
6 = read and write (4+2)
7 = read and write and execute (4+2+1)
• Never set write permission for all other users on a file or directory which is in your home
directory. If you do other users will be able to change its content. This can represent a
serious security risk.
• The umask command is used to set your default file permissions. Typically, the umask
command is included as part of your .profile, .cshrc or .login file.
The umask command accepts only octal specifications. Note that these are different than
those used by the chmod command, and in fact, represent which permissions to "mask
out", or remove.
umask 077
- Subtracts 077 from the system defaults for files
(666) and directories (777). Results in default
access permissions for your files of 600
(rw-------) and for directories of 700
(rwx------).
umask 002
- Subtracts 002 from the sytem defaults to give a
default access permission for your files of 664
(rw-rw-r--) and for your directories of 775
(rwxrwxr-x).
umask 022
- Subtracts 022 from the system defaults to give a
default access permission for your files of 644
(rw-r--r--) and for your directories of 755
(rwxr-xr-x).
Introduction to UNIX
Filesystem Exercises
Parimal Sudas Page 30
These exercises will familiarize you with the basic UNIX commands for working with files and filesystems.
Setup
1. Open a new window or use an existing open window. To open a new window, press and hold
the right mouse button. A "pop up" menu will appear. Still holding the right mouse button, drag
the pointer to the selection which says "New Window". When it is selected (the item will appear
highlighted or raised), release the right button. A new window will appear in a second or two.
2. Change to this exercise's subdirectory by using the command:
3.
4. cd ~/Filesystem
ls
4. Use ls without any arguments to display this directory's contents. How many files do you see?
5. Now use ls with the -a option. How many files do you see this time? Notice that the "new" files
all begin with a "dot", which indicates they are "hidden" files.
6.
7. ls -a
8. This command is useful for distinguishing between directories, ordinary files, and executable
files. Notice how its output differs from ls without arguments.
9.
10. ls -F
11. Use the command ls -l to obtain a "long" listing of your files. Sample output from this command
and an explanation of the information it provides appears below.
12.
13. -rwxr-xr-x 1 jsmith staff 43 Mar 23 18:14 prog1
14. -rw-r--r-- 1 jsmith staff 10030 Mar 22 20:41 sample.f
15. drwxr-sr-x 2 jsmith staff 512 Mar 23 18:07 subdir1
16. drwxr-sr-x 2 jsmith staff 512 Mar 23 18:06 subdir2
17. drwxr-sr-x 2 jsmith staff 512 Mar 23 18:06 subdir3
18. 1 2 3 4 5 6 7
19.
20. 1 = access modes/permissions
21. 2 = number of links
22. 3 = owner
23. 4 = group
27. Recursive listings can be very useful. Try both of the commands below. What does the output
tell you?
28.
29. ls -R
30. ls -Rl
more
7. As you are reading, notice the "More" prompt at the bottom of the page.
8. Try pressing the return key - what happens?
9. Try pressing the space bar once - what happens?
10. Type the letter b - what happens?
11. Use the search forward feature to find the word "MARCH" by entering the command:
12.
13. /MARCH
14. Now use the search backward feature to find the words "black hole" by entering the command:
15.
16. ?black hole
17. more will continue until the end of the file is reached or until you type q for quit. Try typing q to
quit.
4. Display the top of a file with the command below. How many lines do you count?
5.
6. head nasa.94
7. Now try this command and note how many lines are displayed this time?
8.
9. head -5 nasa.94
10. Read/scan the man page for tail with the command:
11.
12. man tail
13. Display the same file with the tail command. How is it different and how many lines do you
count?
14.
15. tail nasa.94
16. Now try this command and note how many lines are displayed this time?
17.
18. tail -5 nasa.94
cat
7. Now try this command notice the difference. How many lines are in the file?
8.
9. cat -n nasa.94
10. The cat command is more often used for purposes other than just displaying a file. Try these
commands to "concatenate" two files into a new, third file:
11.
12. cat file1 - first, show file1
cp
4. Copy an existing file in your current directory to another file in the current directory and then
list your directory to prove that it was done:
5.
6. cp sample.f sample2.f
7. ls
8. Copy a file from a different directory to your current directory and then list your directory to
prove that it was done:
9.
10. cp /etc/environment my.environment
11. ls
12. Use the copy command with the "inquire" option. What happens?
13.
14. cp -i sample.f sample2.f
15. Use the recursive option to copy an entire subdirectory to a new subdirectory and then list both
directories to prove that it worked:
16.
17. cp -R subdir1 subdir4
18. ls subdir1 subdir4
19. The copy command accepts "wildcard" characters. Try the command below. What did it do? List
the subdir1 subdirectory to find out.
20.
21. cp samp* subdir1
22. ls subdir1
23. If you are copying a file from another location to the current directory and want its name to
remain the same, you can use the shorthand "." to indicate the current directory. Try this for
example and note what happens:
24.
25. cp /etc/environment .
26. ls
4. The mv command can be used for renaming files. Try this command and then list your files to
prove that the command worked:
5.
6. mv sample2.f new.sample
7. ls
8. mv can be used to rename directories also. Try this command and then list your files to prove
that the command worked:
9.
10. mv subdir4 dir4
11. ls
12. The mv command is also used for moving files. Use the command below to move new.sample
into a new location, then list your files to prove that the command worked:
13.
14. mv new.sample dir4
15. ls
16. ls dir4
17. Like many other UNIX commands, mv recognizes wildcard characters. Try the command below
and then list your files to prove that the command worked:
18.
19. mv *env* dir4
20. ls
21. ls dir4
rm
4. Use the rm command to delete a file. List your directory after the command completes.
5.
6. rm sample.f
7. ls
14. Get out of the subdir2 subdirectory by using the command cd .. Now try to use rm to remove a
directory. What happens?
15.
16. cd ..
17. rm subdir3
18. This time, include the -r option when you try to remove a directory. What happens?
19.
20. rm -r subdir3
21. ls
22. Return to the tutorial to learn about the next section before proceeding.
file
7. Now use the find command to find all files with "file" as part of their name. Don't forget to put
the wildcard specification in quotes - it won't work otherwise:
8.
9. find . -name 'file*' -print
10. Try to find only directories with "file" as part of their name. Are there any?
11.
12. find . -name 'file*' -type d -print
4. Use the diff command to determine the differences between two files:
5.
6. diff names1 names2
7. Use the diff command to determine the differences between two directories.
8.
9. diff subdir1 dir4
10. Try using sdiff to display the differences between names1 and names2:
11.
12. sdiff names1 names2
13. Now try sdiff specifying that the screen width is 80 characters...not the default 130:
14.
15. sdiff -w 80 names1 names2
4. Create a link between two files in the same directory. Use ls -l to list your directory afterwards
to confirm that the link was done:
5.
6. ln names1 linknames
7. ls -l
8. Create a link between two files in different filesystems. Note that you'll need the -s option to
accomplish this. Use ls -l to list your directory afterwards to confirm that the link was done.
Notice how the link is identified in the listing.
9.
10. ln -s /etc/environment myenv
11. ls -l
12. Use the rm command to remove both of the links. Note that the original files will not be
affected.
13.
14. rm linknames
15. rm myenv
16. ls -l
sort
4. Use the cat command to look at an unsorted list of names. Notice that there are multiple
columns of information and that the list is not alphabetically sorted.
5.
6. cat name.list
10. Do the same sort, but send the output to a file. Then use the cat utility to view the file:
11.
13. Sort the list by first names. This requires skipping over the first field, which is the last name:
14.
15. sort +1 name.list
16. Sort the list by department. This requires skipping over the first four fields and using the -b
option to ignore blank characters:
17.
18. sort -b +4 name.list
19. Return to the tutorial to learn about the next section before proceeding.
pwd
4. Issue the pwd command to display the name of your current working directory:
5.
6. pwd
7. Change to several other directories and issue the pwd command between each change. Notice
the different outputs:
8.
9. cd dir4
10. pwd
11. cd /usr/bin
12. pwd
13. cd /var/spool
14. pwd
15. cd ~/Filesystem
16. pwd
mkdir
9. Now create some additional subdirectories within your newdir. List newdir after the command
completes to prove that it worked:
10.
11. mkdir newdir/sub1 newdir/sub2 newdir/sub3
12. ls newdir
13. Try to create a directory in a location where you don't have permission. What happens?
14.
15. mkdir /etc/mydir
cd
7. Change to a subdirectory within you home directory and list its contents:
8.
9. cd Filesystem/dir4/subdir1
10. ls
11. Go up one level to the current directory's parent directory and list the contents:
12.
13. cd ..
14. ls
15. Change to the root (top-most) directory and list the contents:
16.
17. cd /
18. ls
23. Change to another one of your subdirectories and list the contents:
24.
25. cd ~/Filesystem/newdir
26. ls
rmdir
4. First make sure you are in the Filesystem directory. Then try to remove the newdir directory.
What happens?
5.
6. cd ~/Filesystem
7. rmdir newdir
8. Recursively list the contents of newdir. Notice that its subdirectories are all empty. Remove all
of the empty subdirectories within newdir and then list newdir again to confirm that they were
removed:
9.
10. ls -R newdir
11. rmdir newdir/*
12. ls -R newdir
16. Return to the tutorial to learn about the next section before proceeding.
1. Make sure that you are in your Filesystem exercise directory, and then do a long listing of your
files:
2.
3. cd ~/Filesystem
4. ls -al
5. Notice the access permissions assigned to each file. Can you tell:
o which files are directories?
o if a file is executable?
o who has write access to each file?
o who has read access to each file?
o who owns the file?
o which group the owner belongs to?
o which permissions the group has?
o which permissions others have?
6. Use the chmod command to change the permissions for some files. List the file before and after
each change and determine how the command changes the file permissions.
7.
8. ls -l names1
9. chmod o-r names1
10. ls -l names1
11.
12. ls -l names2
13. chmod g+w names2
14. ls -l names2
15.
16. ls -l file*
17. chmod go-r file*
18. ls -l file*
24. Look in your ~/.cshrc file and find where your umask setting is specified. What is it and what
does it do? How would you change it so that nobody except you could see your files?
28. Return to the tutorial to learn about the next section before proceeding.
Introduction to UNIX
Standard UNIX File System Exercises
These exercises will familiarize you with the overall organization of your UNIX filesystem.
1. Change directory to the root level and then list the contents.
2.
3. cd /
4. ls
How many files do you see which are mentioned in the tutorial as being common/standard UNIX
files?
5. Change to the /usr directory and list it, again noting how many files you see which are
mentioned in the tutorial as being common/standard UNIX files?
6.
7. cd /usr
8. ls
9. Spend some time navigating about the upper levels of the filesystem.... see how lost you can
get!! Try some of the other directories mentioned in the tutorial.
Don't forget that you can always use the pwd command to tell you where you are, and the
cd command to return to your home directory.
Unix Editors
• What is a text editor?
o A text editor is a program which enables you to create and manipulate character
data (text) in a computer file.
o A text editor is not a word processor although some text editors do include word
processing facilities.
vi Commands
• Entering vi
•
• vi filename - The filename can be the name of an
• existing file or the name of the file
• you want to create.
• view filename - Starts vi in "read only" mode. Allows
• you to look at a file without the risk
• of altering its contents.
• Exiting vi
•
• :q - quit - if you have made any changes, vi
• will warn you of this, and you'll need
• to use one of the other quits.
• :w - write edit buffer to disk
• :w filename - write edit buffer to disk as filename
• :wq - write edit buffer to disk and quit
• ZZ - write edit buffer to disk and quit
• :q! - quit without writing edit buffer to disk
• Inserting text
•
• a - append text after cursor *
• A - append text at end of line *
• i - insert text before cursor *
• I - insert text at beginning of line *
• o - open a blank line after the current
• line for text input *
• O - open a blank line before the current
• line for text input *
•
• * Note: hit ESC (escape) key when finished inserting!
• Changing text
•
• cw - replace word with text *
• cc - replace line with text *
• c0 - change to beginning of line *
• c$ - change to end of line *
• C - change to end of line *
• c( - change to beginning of sentence *
• c) - change to end of sentence *
• c{ - change to beginning of paragraph *
• c} - change to end of paragraph *
• r - overtype only 1 character
• R - overtype text until ESC is hit *
• J - join two lines
•
• * Note: hit ESC (escape) key when finished changing!
• Copying lines
•
• yy - "yank": copy 1 line into buffer
• nyy - "yank": copy n lines into buffer
• Searching / Substituting
•
• /str - search forward for str
• ?str - search backward for str
• n - find next occurrence of current string
• N - repeat previous search in reverse
• direction
•
• The substitution command requires a line range
• specification. If it is omitted, the default
• is the current line only. The examples below
• show how to specify line ranges.
•
• :s/old/new - substitute new for first occurrence
• of old in current line
• :s/old/new/g - substitute new for all occurrences
• of old in current line
• :1,10s/old/new - substitute new for first occurrence
• of old in lines 1 - 10
• :.,$s/old/new - substitute new for first occurrence
• of old in remainder of file
• :.,+5s/old/new - substitute new for first occurrence
• of old in current line and next 5 lines
• :.,-5s/old/new - substitute new for first occurrence
• of old in current line and previous
• 5 lines
• :%s/old/new/g - substitute new for all occurrences
• of old in the entire file
• :%s/old/new/gc - interactively substitute new for all
• occurrences of old - will prompt for
• y/n response for each substitution.
• Miscellaneous commands
Parimal Sudas Page 48
•
• u - undo the last command (including undo)
• . - repeat last command
• xp - swap two adjacent characters
• m[a-z] - set a marker (a - z)
• '[a-z] - go to a previously set marker (a - z)
• :!command - execute specified UNIX command
• :r filename - read/insert contents of filename after
• current line.
• :1,100!fmt - reformat the first 100 lines
• :!fmt - reformat the entire file
vi Options
• You can change the way vi operates by changing the value of certain options which
control specific parts of the vi environment.
• To set an option during a vi session, use one of the commands below as required by the
option:
•
• :set option_name
• :set option_name=value
• Options can be set permanently by putting them in a file called .exrc in your home
directory. A sample .exrc file appears below. Note that you do not need the colon (:) as
part of the option specification when you put the commands in a .exrc file. Also note that
you can put them all on one line.
•
• set nu ai wm=5 showmode ic
Introduction to UNIX
Editor Exercises
These exercises will familiarize you with the vi and pico editors.
Starting a vi Session
1. Open a new window or use an existing window for this exercise. Change directory to where the
editor exercises are located and list the files:
2.
3. cd ~/Editors
4. ls
8. When the file appears on your screen, you will note several things:
o the file name and size appear at the bottom of the screen
o the cursor is in the top left corner of the screen
o one screen full of text appears, beginning with the first line in the file
o there are numerous mistakes and errors in the text...we'll deal with fixing these later.
IMPORTANT: The vi editor will always start in the command mode - whatever you type
will be interpreted as commands, not as text to be inserted.
1. Knowing how to position the cursor is important, since many vi commands use the cursor as the
reference point on where to execute the command.
2. Practice moving the cursor one character at a time:
3.
4. left arrow - left one character
5. right arrow - right one character
6. backspace - left one character
7. space - right one character
8. h - left one character
9. l - right one character
49. Return to the tutorial to learn about the next section before proceeding.
Inserting Text
1. The "other" vi mode is the insert mode. In this mode, your typing will be interpreted as text to
be added to the document.
2. Assuming that you are still editing the ~/Editors/practice.1 file, put your cursor at the beginning
of the file (1G). Then place it on the first letter of the word: PEOPLE
3. Use the i command to put yourself in the insert mode. Now whatever you type will be text
added to the file. Type the word THE. Press the Esc key when you are finished to leave the insert
mode. The title should now say "THE PEOPLE OF HAWAII".
4. Now move your cursor to the last line of the first paragraph. This sentence obviously needs
completed. Use the o command to open a new line under the current line. This will put you into
the insert mode. Type the new line: Mainland U.S., and 15% are foreign-born. Press the Esc key
when you are finished to leave the insert mode.
5. The second line in the second paragraph is missing a word at the end of the line. Move your
cursor to this line. Then use the A command to append the word lowest at the end of the line.
Press the Esc key when you are finished to leave the insert mode.
6. The next line is also missing a word. Move your cursor to the end of the word permanent. Then
use the a command to append the word residents. Press the Esc key when you are finished to
leave the insert mode.
7. Save your editing changes to disk by typing the command :w Note that it is a good idea to save
your editing changes to disk frequently. This will help avoid losing work should your system
crash, or you accidentally kill your vi session.
8. Return to the tutorial to learn about the next section before proceeding.
Deleting Text
1. Assuming that you are still editing the ~/Editors/practice.1 file, note that the last word in the
second paragraph is spelled incorrectly. Move your cursor to the word livving. Place the cursor
directly on one of the v characters. Type x to delete it.
2. The first sentence of the third paragraph is exaggerating things a bit. Move your cursor to the
beginning of the word billion. Type the command 2dw to delete the two words billion trillion
Changing Text
1. Assuming that you are still editing the ~/Editors/practice.1 file, return your cursor to the
beginning of the second paragraph. In the second line, you'll see the words changed wildly.
Place your cursor on the first character of the word changed. Use the cw command to change
this word to the word fluctuated.
Notice the dollar sign which appears. This shows you the end of the word which is being
changed. Notice also, that changing text puts you into the insert mode. You must press
the Esc key to exit the insert mode when you are finished with your change.
2. Now move your cursor down four more lines and find the words radically segregated. Put your
cursor on the first character of the word "radically". Then use the command 2cw to change
these two words to racially integrated. Press the Esc key to exit the insert mode when you are
finished with your change.
3. In the next line, the number 800,000 should be changed to 400,000. Put the cursor on the
number 8. Type r followed by the number 4. This command only replaces a single character, so
there is no need to press the Esc key.
4. The next line has another number which needs corrected. Put your cursor at the beginning of
the number 594,342. Type the R command followed by 500,000. You must press the Esc key to
exit the insert mode when you are finished with your change.
5. Move your cursor to the first line of the third paragraph. It can be joined with the short line
beneath it. Join this line to its following line with the J command. You should now have a single
line which reads, "Of the one million people in the islands today, 800,000 live on Oahu,".
6. When you are finished with the above changes, save the file and exit this vi session by typing the
command :wq or the command ZZ
7. If desired, you can compare your practice.1 file to the practice.1.final file. They should be very
close if not identical.
8. Return to the tutorial to learn about the next section before proceeding.
1. Assuming that you are still in your ~/Editors directory. Begin this exercise by editing the
practice.2 file with the command vi practice.2
2. Notice the three lines near the top of the document which look something like this:
3. ***********************************************************************
****
4. Chapter 1
5. ***********************************************************************
****
6. Copy these lines by moving your cursor to the first of the three and typing the command 3yy.
This will "yank" them into the copy buffer. Notice that the lines do not disappear...they are
copied.
7. Now move your cursor to the blank line which separates the first paragraph from the second
paragraph. Put the copied lines under this line by typing the p command.
8. Since you haven't performed any new editing commands which would overwrite the copy buffer
(such as a delete or another yank), the buffer contents are still intact. Now move your cursor to
the first line of the third paragraph.
9. Put the copied lines above this line by typing the P command.
10. Change the headings on the second and third paragraphs to indicate "Chapter 2" and "Chapter
3" accordingly. Use whatever "change text" editor command you wish for this.
11. Save your editing changes to disk by typing the command :w
1. Assuming that you are still editing the ~/Editors/practice.2 file, swap the first paragraph with
the second paragraph by following the steps below.
2. Place your cursor on the first non-heading line of the first paragraph - it begins, "A Hawaiian
tsunami is actually...". There should be seven lines in this paragraph. "Cut" these lines by using
the command 7dd. They will be placed in the copy/cut buffer.
3. Now, move your cursor to the first non-heading line of the second paragraph - it begins,
"Tsunami is the Japanese word for....". "Paste" the lines you just "cut" above this line by using
the P command.
4. Move the cursor down to what used to be the first line of the second paragraph - it begins,
"Tsunami is the Japanese word for ..."
5. "Cut" these five lines with the 5dd command. Note that these lines will be saved in the copy/cut
buffer, overlaying anything else which was there.
6. Move your cursor to the third "heading" line at the top of the document. It should be on a row
of asterisks.
7. "Paste" the new first paragraph under these asterisks by typing the p command.
8. When you are finished with the above changes, save the file and exit this vi session by typing the
command :wq or the command ZZ
9. If desired, you can compare your practice.2 file to the practice.2.final file. They should be very
close if not identical.
Searching / Substituting
1. Assuming that you are still in your ~/Editors directory, begin this exercise by editing the file
practice.3. This file is somewhat larger than the previous two files. In real editing jobs, files can
be very sizeable. Being able to search quickly through a large document is an important time
saver. Knowing how to make global changes can also save lots of time.
2. You discovered that somewhere in your document the word "lingers" has been spelled
incorrectly as "ligers". Find the incorrect word by using the command /ligers and then correct it.
3. You also discovered another typo. Find the misspelled word "famly" with the command /famly
and change it to "family".
4. Return to the first paragraph near the top of the document. Place your cursor at the beginning
of the first line. Notice the grammatical mistake in this sentence - the word "natives" should be
"native". Make the change using the substitution command:
5.
6. :s/natives/native/
7. The word "kahuna" has been misspelled as "kahuuna" in a number of places. Rather than finding
and changing every occurrence individually, do a global substitution with the command
8.
9. :%s/kahuuna/kahuna/gc
Note that the gc option is used, which cause you to be prompted for each change. Enter either a
"y" or "n" for "yes" or "no". Omitting the c will cause the substitutions to occur without
prompting.
10. Find and remove all of the lines which look something like:
You could do a global substitution, however, it would fail if any occurrence had extra spaces,
was missing the period, or was even slightly different in any way.
One method for making sure they are all changed is described below:
1.
Return your cursor to the top of the document
2.
Search for the first occurrence with the command /Return
3.
When it is found, delete it with the dd command
4.
Find the next occurrence with the n command
5.
Delete it as before and repeat the n and dd commands until all occurrences have been
removed.
11. When you are finished with the above changes, save the file and exit this vi session by typing the
command :wq or the command ZZ
Parimal Sudas Page 56
12. If desired, you can compare your practice.3 file to the practice.3.final file. They should be very
close if not identical.
13. Return to the tutorial to learn about the next section before proceeding.
Miscellaneous Commands
Assuming that you are still in your ~/Editors directory, begin this vi editing session with the practice.3
file.
1. Setting Markers
2. The use of markers can save time by allowing you to jump back and forth quickly
between different parts of the document.
3. Put your cursor at the beginning of the file. Use the search command /Polynesian Roots
to find the beginning of Polynesian Roots section. You will probably encounter the first
occurrence in the outline. Ignore this one and repeat the search by just typing /
4. Set marker "a" here by using the command ma
5. Now use the search command /Fatal Flaws to find the beginning of that section.
6. Set marker "b" here by using the command mb
7. Practice jumping back and forth between marker a and marker b with the commands 'a
and 'b
8. Let your imagination roam on just how useful 26 markers (a-z) can be. If you ever use
more than five, you'll either make the Guiness Book or create a file nobody can figure
out.
9. Reading and Writing Other Files
10. Go to the beginning of the practice.3 file. Add an item #8 to the Table of Contents. Call it
"Madame Pele". What? You want the commands on how to do this? We already learned
that. OK, here they are:
11.
12. 1G
13. /7
14. o
15. 8. Madame Pele
16. Esc the escape key - don't type "Esc"
17. Now go to the end of the document and place your cursor on the very last line. Then,
use the command :r pele.txt to read in a file which contains a story about the goddess
Pele. Read the story if you wish - Pele would insist. A volcano will erupt if you don't.
18. Save your modified practice.3 file as a new and different file with the command
19.
20. :w new.practice.3
Note that this will not change the fact that you are still editing the file practice.3.
This means you can create virtually any file you wish from within a vi session.
25. You should see a long listing of your working directory which includes the
new.practice.3 file. Notice that vi will prompt you to hit the return key to resume
editing.
26. Other UNIX commands can be executed from within a vi session similarly.
27. Exit this session without saving any changes by using the command :q!
28. !fmt
29. Assuming that you are still in your ~/Editors directory, begin an editing session with the
file kam.txt. After it appears, you'll notice that the lines are formatted rather poorly.
30. Use the command below to reformat the entire file. The dollar sign is simply a
shorthand which means "to the end of the file".
31.
32. :1,$ !fmt
This command can also be used to reformat a range of lines. For example, the command
below would reformat lines 1 - 100.
:1,100 !fmt
33. When you are finished with the above, save the file and exit this vi session by typing the
command :wq or the command ZZ
• Return to the tutorial to learn about the next section before proceeding.
vi Options
1. Assuming that you are still in your ~/Editors directory, edit the file vi.options. As you read it,
you'll notice that it explains several vi options, all of which are non-essential to the function of vi
- they simply set preferences.
2. Try the nu option by typing the command below. What happens?
3.
4. :set nu
5. Experiment with the ai option. You'll have to actually try adding lines of text to observe its
effects.
6. Experiment with the showmode option. You'll have to actually do some text insertions to see
what happens (the words INPUT MODE should appear in the lower right corner when you are in
input mode).
7. Toggle on/off between the options. For example:
11. Exit this editing session without saving anything by using the command :q!
12. Return to the tutorial to learn about the next section before proceeding.
1. pico is so easy to use that you don't even need these instructions. So, they're going to be short.
2. Assuming that you are still in your ~/Editors directory, open a pico editor session with the file
maui.txt
3.
4. pico maui.txt
5. Move around the initial screen with the arrow keys. Then try to type something...notice that
there is no "insert mode" and "command mode" like vi. Your typing is automatically interpreted
as text to insert into the document.
6. Try deleting text, moving the cursor around and adding blank lines
7. Now try cutting/pasting text, reading another file into the current editing session and writing
the buffer out as a different file... and anything else you'd like.
To accomplish tasks, you'll need the correct control character sequences, all of which are
documented in the tutorial or at the bottom of your pico screen.
8. If you have problems, the context-sensitive "help" CTRL-G can be used for assitance.
9. When you are finished, CTRL-X can be used to exit and optionally save the editor buffer as a file.
• Your login shell is usually established by the local System Administrator when your
userid is created. You can determine your login shell with the command:
echo $SHELL
• Each shell has a default prompt. For the 5 most common shells:
•
• $ (dollar sign) - sh, ksh, bash
• % (percent sign) - csh, tcsh
• Depending upon the shell, certain features will be available. The table below summarizes
the features available with the 5 most common shells. Note: these features will be
described in detail later.
•
• Bourne C TC Korn BASH
• sh csh tcsh ksh bash
• ______________________________________________________
• Programming language Yes Yes Yes Yes Yes
• Shell variables Yes Yes Yes Yes Yes
• Command alias No Yes Yes Yes Yes
• Command history No Yes Yes Yes Yes
• Filename completion No Yes* Yes Yes* Yes
• Command line editing No No Yes Yes* Yes
• Job control No Yes Yes Yes Yes
• ______________________________________________________
•
• * not the default setting for this shell
% ps
PID TTY TIME CMD
26450 pts/9 0:00 ps
66801 pts/9 0:00 -csh
To see a detailed list of all of your processes on a machine (current shell and all other
shells):
% ps uc
USER PID %CPU %MEM SZ RSS TTY STAT STIME TIME COMMAND
jsmith 26451 0.0 0.0 120 232 pts/9 R 21:01:14 0:00 ps
jsmith 43520 0.0 1.0 300 660 pts/76 S 19:18:31 0:00 elm
jsmith 66801 0.0 1.0 348 640 pts/9 S 20:49:20 0:00 csh
jsmith 112453 0.0 0.0 340 432 pts/76 S Mar 03 0:00 csh
% ps ug
USER PID %CPU %MEM SZ RSS TTY STAT STIME TIME COMMAND
root 0 0.0 0.0 8 8 - S Feb 08 32:57 swapper
root 1 0.1 0.0 252 188 - S Feb 08 39:16
/etc/init
root 514 72.6 0.0 12 8 - R Feb 08 28984:05 kproc
root 771 0.2 0.0 16 16 - S Feb 08 65:14 kproc
root 1028 0.0 0.0 16 16 - S Feb 08 0:00 kproc
{ lines deleted }
root 60010 0.0 0.0 1296 536 - S Mar 07 0:00 -ncd19:0
kdr 60647 0.0 0.0 288 392 pts/87 S Mar 06 0:00 -ksh
manfield 60968 0.0 0.0 268 200 - S 10:12:52 0:00 mwm
kelly 61334 0.0 0.0 424 640 - S 08:18:10 0:00 twm
• kill - use the kill command to send a signal to a process. In most cases, this will be a kill
signal, hence the command name. However, other types of signals are usually supported.
Note that you can only kill processes which you own. The command syntax is:
Examples:
You can also use CTRL-C to kill the currently running process.
To start a job in the background, use an ampersand (&) when you invoke the command:
myprog &
To put an already running job in the background, first suspend it with CRTL-Z and then
use the "bg" command:
• Foreground a process: To move a background job to the foreground, find its "job"
number and then use the "fg" command. In this example, the jobs command shows that
• Stop a job running in the background: Use the jobs command to find its job number, and
then use the stop command. You can then bring it to the foreground or restart execution
later.
•
• jobs
• [1] + Running xcalc
• [2] Running find / -name core -print
• stop %2
• Kill a job running in the background, use the jobs command to find its job number, and
then use the kill command. Note that you can also use the ps and kill commands to
accomplish the same task.
•
• jobs
• [1] + Running xcalc
• [2] Running find / -name core -print
• kill %2
Redirection
• Redirection refers to changing the shell's normal method of handling standard output
(stdout), standard input (stdin) and standard error (stderr) for processes. By default, all of
these are from/to your screen.
• Examples:
•
• mail tony < memo - uses the file memo as input
• to the mail program
• ls -l > my.directory - redirects output of ls -l
• command to a file called
• my.directory. If the file
• already exists, it is
• overwritten
• cat Mail/jsmith >> Oldmail - appends the contents of
• Mail/jsmith to the file
• Oldmail (does not overwrite)
• myprog >& output - redirects stdout and stderr
• from myprog's execution to
• a file called output
• (csh,tcsh)
• (myprog > out) >& err - redirects stdout from myprog's
• execution to a file called out
• and stderr to the file err
• (csh,tcsh)
• myprog 2> runtime.errors - redirects stderr from
• myprog's execution to a
• file called runtime.errors
• (sh,ksh,bash)
• myprog > output 2>& - redirects stderr and stdout
• from myprog's execution
• to a file called output
• (sh,ksh,bash)
• myprog > out 2> err - redirects stdout from myprog's
• execution to a file called out
• and stderr to the file err
• (sh,ksh,bash)
• Pipes accomplish with one command what otherwise would take intermediate files and
multiple commands. For example, operation 1 and operation 2 are equivalent:
•
• Operation 1
• who > temp
• sort temp
•
• Operation 2
• who | sort
Filters
• A filter is a command that processes an input stream of data to produce an output stream
of data.
• Command lines which use a filter will include a pipes to connect it to the stdout of one
process and the stdin of another process.
• For example, the command line below takes the output of "who" and sorts it. The sorted
output is then passed to the lp command for printing. In this example, sort is a filter.
•
• who | sort | lp
• Both filters and pipes demonstrate a basic UNIX principle: Expect the output of every
program to become the input of another, yet unknown, program to combine simple tools
to perform complex tasks.
Features (csh)
Each shell has its own set of features. Those of the C Shell are discussed below.
• Command history: The history mechanism maintains a list of recently used command
lines, called events. Provides a shorthand for reexecuting previous commands. To use
history:
1. Set the history variable:
2.
3. set history = 100
17. To save history events across all login sessions, set the savehistory variable:
18.
19. set savehistory = 50
• Event reexecution: Allows you to specify a shorthand for reexecuting a previous event.
Works with the history list.
•
• !! - repeats last command
• !number - repeats numbered command from history list
• !string - repeats last command starting with string
• Modifying previous events: Allows you to correct typos in previous command, or modify
it to create a new command.
•
• ^old^new - changes the string "old" to the
• string "new" in the last command
• issued
• Aliases: The alias command allows you to define new commands. Useful for creating
shorthands for longer commands. The syntax is.
•
• alias entered_command executed_command
Some examples:
alias m more
alias rm "rm -i"
alias h "history -r | more"
alias xpvm /source/pd/xpvm/src/RS6K/xpvm
alias
unalias alias_name
• Filename Generation: When you give the shell abbreviated filenames which contain
special characters (metacharacters), it can generate filenames which match existing files.
Some examples appear below:
•
• ls *.txt - list files with .txt suffix
• ls [abc]* - list files with names that start with a,
• b or c
• lpr prog?.c - print files named prog?.c where ? is
• any character
• cd ~jsmith - change to user jsmith's home directory
You can "turn off" filename generation by setting the noglob variable. This will permit
special characters to be interpreted literally. For example:
set noglob
To use filename completion, you need to set filec, either on the command line or in one
of your initialization files.
set filec
Then, when specifying a filename, type the part which is unique and hit the escape key (C
shell) or tab key (TC Shell). For example, if you had a directory with a long name, such
as "Introduction.UNIX.Filesystems", you could cd to that directory by using the cd
command with only a portion of the file's name, provided that the portion you specify is
unique (no other files have similar names)
cd Intro<ESC>
Note: typing a portion of a filename and then hitting CTRL-D instead of ESCape or TAB
will display a list of the filenames which match.
Variables (csh)
Each shell has its own set of variables and rules for using variables. Those associated with the C
Shell are discussed below.
• The shell has variables which are predefined as well as variables which you define (user
defined).
• Shell variables control many aspects of how your shell environment behaves. Modifying
these variables (and creating new ones) allows you to customize your shell environment.
• Shell variables are used extensively when creating shell scripts (covered later).
• Variables can be
o local - current shell only
o global - current shell and child processes/shells
o string - treated as character
o numeric - treated as numbers
o arrays - contain more than one value
• Commands used to declare and manipulate shell variables:
•
• set - assigns non-numeric string variables
• locally
• unset - removes a previously "set" variable
• set - shows all "set" variables
• setenv - assigns non-numeric string variables
Parimal Sudas Page 68
• globally
• unsetenv - removes a previously setenv variable
• setenv - shows all setenv variables
• @ - assigns numeric variables locally
• echo $variable - displays value of variable
• Examples
•
• set name=fred - Sets variable name to
• value of fred
• unset name - Unsets the variable name
• set path=($path . ~/bin) - Adds to current setting
• of string array variable
• path
• setenv DISPLAY makena:0 - Sets environment variable
• DISPLAY
• echo $HOME - Displays value of variable
• HOME
• set colors=(red green blue) - Assigns three values to
• the string array variable
• colors
• @ count = 1 - Sets numeric variable
• count to one
• @ count = ($count + 1) - Adds one to numeric
• variable count
• set counts = (1 22 4 9) - Assigns 4 values to
• numeric array variable
• counts
• @ counts[2] = 5 - Assigns values to second
• element of numeric array
• variable counts
• @ echo $counts[3] - Displays value of third
• element of numeric array
• variable counts
• Predefined Shell Variables. A number of shell variables are predefined by the shell itself
or inherited from the system environment. Some of the more common ones are described
below.
$
Contains the process id of the current shell
argv
Contains the command line arguments for an invoked command. argv is an array, with
$argv[0] set to the name of the invoked command, $argv[1] set to the first argument,
$argv[2] set to the second argument...and so on. $argv[*] can be used to specify all
arguments. You may also use the shorthand $n where n is the number of the argument.
Initialization Files
• System-wide shell initialization files are common on UNIX systems. These files can be
"sourced" automatically by the shell and are typically setup by the System Administrator
for the local environment.
• Some examples of system-wide initialization files might be:
•
• /etc/environment
• /etc/profile
• /etc/cshrc
• /etc/login
• Every shell provides a means for the user to customize certain aspects of the shell's
behavior. These customizations usually permit you to augment and/or override the
system-wide defaults.
• User customizations are specified in initialization files located in the top level of your
home directory.
• Naming: Depending upon the shell, you must name your initialization file(s) accordingly.
•
• Executed during interactive login
• .login - csh, tcsh
• .profile - sh, ksh, bash
• .bash_profile - bash (alternative 1)
• .bash_login - bash (alternative 2)
•
• Executed for every new shell
• .cshrc - csh, tcsh
• .tcshrc - tcsh
• .kshrc - ksh
• .bashrc - bash
• The system administrator may/may not provide you with default .cshrc and .login files
when you first obtain your userid. If they are provided, be careful about modifying them -
especially removing specifications which are required for your local system.
• Example .cshrc and .login files are provided below:
o .cshrc file
o .login file
• Continue the Shell Exercises
Logout Files
• You are able to specify commands which the shell will execute upon logout. These
commands are kept in a file located in the top level of your home directory.
•
• .logout> - csh, tcsh
• .bash_logout - bash
Introduction to UNIX
Shell Exercises
Determining Your Shell
1. Open a new window or use an existing window for this exercise. Then make sure that you are in
the Shell subdirectory:
2.
15. Try invoking other shells and notice how the prompt changes. Then list your processes to see
them
16.
17. sh
18. csh
19. ksh
20. bash
21. ps
22. Return to your original shell by exiting consecutively from each of the shells you started above.
List your processes to verify that you have only your original (tcsh) shell running:
23.
24. exit
25. exit
26. exit
27. exit
28. ps
29. Return to the tutorial to learn about the next section before proceeding.
Processes
4. Try using the ps command to list your processes. Then try to list other processes on the system.
For example:
5.
13. Start a process which does nothing except sleep for 5000 seconds
14.
15. sleep 5000
Now try issuing some other commands, for example ls. What happens? Why won't the shell
accept any commands?
16. To kill a process which is running in the foreground, CTRL-C can usually be used. Kill the sleep
5000 process you just started in this manner. What happens after you kill the process? Try
another UNIX command, such as ls. Does it work now?
17. Start another sleep 5000 process, except this time, start it in the background:
18.
19. sleep 5000 &
Now try issuing some other commands, for example ls. What happens?
20. Use the jobs command to find out about jobs you have running in the background. What does
the output of the jobs command tell you?
Start a couple more sleep 5000 processes in the background and then use the jobs
command again. Do they all appear?
21. Bring the third sleep process into the foreground with the command fg %3 What happens? Can
you run anything else now? Why?
22. Suspend the foreground sleep process with the CTRL-Z command. What happens? Try the jobs
command now. What does it show?
23. A suspended process can be put in either the background or foreground. Use the bg %3
command to resume running the third sleep process in the background.
24. The kill command can be used in various ways. Kill the third sleep process with the command kill
%3 and then use the jobs command to check on it. What do you see?
25. Now use the ps command to view your processes. Do you see the remaining two sleep
processes? Notice their PIDs and then use the kill command to kill both of them. For example:
26. % ps
27. PID TTY TIME CMD
28. 15493 pts/0 0:00 sleep 1000
29. 18054 pts/0 0:00 sleep 1000
39. Return to the tutorial to learn about the next section before proceeding.
Redirection
1. Redirect the output of the man command into a file instead of to your screen with the
command:
2.
3. man cp > cp.manpage
List your directory to confirm that the command worked. View the file with the more
cp.manpage command also.
4. Redirect the output of the ls -l command to a file and then view the file after the command
completes:
5.
6. ls -l ~/* > homedir.files
7. Redirect the input for mail by sending a file as the mail message. No interactive prompting will
be done by mail. Don't forget to substitute your userid and node number for the Xs below.
8.
9. mail studntXX@nodeX.class.mhpcc.edu < homedir.files
10. Redirect both the stdout and stderr from a command to a file. For example, type the command
ls * nosuchfile and notice that both the command output and an error message are displayed on
your screen. Then, type the command below to redirect both to a file. View the file after the
command completes.
11.
12. ls * nosuchfile >& ls.out-err
13. Redirection will overwrite existing files. To prove it, try the following sequence of commands:
14.
15. echo 'one' > file1
16. cat file1
17. echo 'two' > file1
19. You can append redirected output to an existing file if you use >> instead of >. Try to commands
below to prove it:
20.
21. echo 'one' > file1
22. cat file1
23. echo 'two' >> file1
24. cat file1
25. Redirection of both stdin and stdout can also be used. Assuming that you are still in your ~/Shell
directory, the following command will use the file unsorted as input to the sort utility and
produce a sorted file called sorted.list.
26.
27. sort < unsorted > sorted.list
28. Return to the tutorial to learn about the next section before proceeding.
1. Obtain a sorted list of users on the system by piping the output of the who command to the
input of the sort command:
2.
3. who | sort
4. View all system processes one screen at a time by piping the output of the ps ug command to
the input of the more command:
5.
6. ps ug | more
7. View all studntXX processes one screen at a time by piping the output of the ps ug command to
the input of the grep command:
8.
9. ps ug | grep studnt
10. View all root processes one screen at a time by piping the output of three different commands
together. Note that in this example, the grep command is acting as a filter:
11.
12. ps ug | grep root | more
13. Return to the tutorial to learn about the next section before proceeding.
1. Command History: The student userids have already been setup to use the C Shell's command
history feature. To view your command history simply type the command history. What do you
see?
2. You may wish to view your command history in reverse chronological order (most recent
commands at beginning of list), one screen at a time:
3.
4. history -r | more
5. The student userids have been setup to use the Tcsh, which is an extended version of the C
Shell. It allows you to "cycle through" your command history by using the up arrow key. Try
pressing your up arrow key at the Shell prompt. Try it several times. Your previous commands
should appear, allowing you to edit them and/or press return to reexecute them.
6. Event Reexecution: Try reexecuting several events from your history list. An example is shown
below - note that your actual command history will differ:
7. % history -r more
8. 36 12:34 cat sorted.list
9. 35 12:34 sort < unsorted > sorted.list
10. 34 12:34 ls -l > unsorted
11. 33 12:32 sort < ls * > sorted.list
12. 32 12:23 ps ug | grep studnt
13. 31 12:22 ps ug | grep root | more
14. 30 12:20 ps ug | more
15. 29 12:18 ps aux
16. 28 12:16 ls
17. % !36
Now try reexecuting an event by using the !string method. For example, the command !his will
reexecute the last command you issued which began with the string "his" (such as a history
command).
18. Modifying Previous Events: First, type a command with an obvious typo:
19.
20. sort unsrted | grep Systems
After the shell tells you it can't open the file "unsrted", modify the command as shown below.
The command should now work.
^srt^sort
21. Using Aliases: Create a few aliases and then use them:
22.
23. alias h "history -r | more"
24. h
25. alias ll "ls -l"
26. ll
27. alias rm "rm -i"
28. rm unsorted
Issue the alias command without any arguments. It should show you all of your defined aliases.
29. Filename Generation: You have been using this feature all along. For example:
30.
31. ls ~/Filesystem/*
32. ls ~/Filesystem/file*
33. ls ~/Filesystem/[ns]*
You can turn off filename generation with the command set noglob. Do this and then try the
same commands above. When you're convinced that it is turned off, turn it back on again with
the command unset noglob.
34. Filename Completion: Turn on this feature with the command set filec. Then, create a file with
a long name:
35.
36. touch Introduction.UNIX.Filesystems
Now, type the following and notice what happens. Note that you should use the actual Tab key
instead of the literal words "Tab key". Also note that some systems use the Esc key instead of
the Tab key.
ls IntTab key
37. Return to the tutorial to learn about the next section before proceeding.
Variables
1. Display your shell's variables with the set command. Review the list. Then, use the echo
command to display a few of them individually. For example:
2.
6. The PATH(path) variable is a very important variable. It determines the directory paths which
the shell will search when looking for an executable. Find out what your path is:
7.
8. echo $path
9. echo $path | fold - use this if it "runs off" the
10. right hand side of the screen
11. Display your shell's environment variables with the setenv command. Review the list. Then, use
the echo command to display a few of them individually. For example:
12.
13. echo $HOST
14. echo $MANPATH
15. echo $HOME
20. Set a few variables of your own creation and then display/use them. For example:
21.
22. set myvar1 = "this is a string variable"
23. echo $myvar1
24.
25. setenv dir1 /usr/local/bin
26. ls $dir1
27.
28. set colors=(red green blue)
29. echo $colors[1]
30. echo $colors[2]
31. echo $colors[3]
32. echo $colors
33.
34. @ num1 = 256
35. @ num2 = 512
36. @ num3 = ($num1 + $num2)
37. echo $num3
38. Unset any of the variables you previously set and then try to display them. What happens? For
example:
39.
40. unset colors
41. echo $colors
42.
45. Return to the tutorial to learn about the next section before proceeding.
Initialization Files
1. Change to your home directory and list all of your files including your hidden files. Which
initialization files mentioned in the tutorial do you see?
2.
3. cd
4. ls -a
5. Use either vi or pico to edit your .cshrc file. Notice the variables and aliases which have already
been set for you. Customize the file, perhaps creating some variables or aliases of your own. You
may get an idea or two from the example .cshrc file in the tutorial.
6. Use the command source .cshrc to effect the changes you made. Try them out...do they work?
7. View the system wide initialization file: /etc/environment. Note in particular how the PATH
variable is set. This is the default path for all users on the system.
mail username@address
2. You will then be prompted to enter the subject of your mail message. Enter the
subject title and press the Return key. If you make a mistake use the Backspace or
Delete key for corrections. For example:
3. Enter the text of your message. Use the Backspace or Delete key for corrections.
Press the Return key whenever you want to start a new line. Note: you can not
back up to previous lines to make corrections. You will need to invoke an editor,
such as vi to accomplish this (covered later).
4. When you are finished typing the message, press the Return key to start a new
line and type CTRL-d. You will then be prompted for any addressees to Cc. You
may either enter additional email addresses or press the Return key if there is
nobody to copy. Your message will be sent and the shell prompt will be
displayed.
•
Control Commands:
CTRL-D - Send message
~q - Quit editor without saving or sending
message
~p - Display the contents of the message buffer
~? - Display help
~:set - Show which mail options are in effect
Add to Heading:
Add to Message:
~d - Append contents of dead.letter to message
~r filename - Append contents of filename to the message
~f numlist - Append contents of message numbers in
numlist
~m numlist - Append/indent contents of message numbers
in numlist
Change Message:
~e - Edit the message using an external
editor (default is e)
~v - Edit the message using an external
editor (default is vi)
~w filename - Write the message to filename
~! command - Start a shell, run command, and return
to the editor.
~| command - Pipe the message to standard input of
command; REPLACE the message with the
standard output from that command.
• Invoking an editor, with either the ~e or ~v command makes creating your message much
easier. If you use ~v, then the vi editor will be used. If you use ~e, you can use a different
editor, such as pico:
•
• ~:set EDITOR=/local/bin/pico - first specify the editor
• of choice
• ~e - then invoke it
• In addition to the ~r command, you can send a file in a mail message as shown below. In
this example, the file "asia.report" will be sent to the address jwwilliams@ibm.vnet.com.
No editing of the mail message is possible - it will be sent directly.
Reading Mail
• To read your mail, simply enter the command:
If you have any mail in your system mail box, an indexed list of the messages will be
displayed on your screen. For example:
Control Commands:
q - Quit - apply mailbox commands entered this
session
x - Quit - restore mailbox to original state
! cmd - Start a shell, run cmd, return to mailbox
- Display Commands:
Return key - Display current message
t - Display current message
t msg_list - Display messages in msg_list
n - Display next message
f msg_list - Display headings of messages in msg_list
h - Display headings or all messages
- Message Handling:
e num - Edit message num (default editor is e)
v num - Edit message num using vi editor
d msg_list - Delete messages in msg_list or current
message
u msg_list - Recall deleted messages
s msg_list file - Append messages (with headings) to file
w msg_list file - Append messages (text only) to file
pre msg_list - Keep messages in system mailbox
• By default, when you start mail, it uses your "system mailbox" as its folder. Your system
mailbox is usually located someplace like /usr/spool/mail or /var/spool/mail. It contains
new mail and previously unread mail.
• You can view other folders by starting mail with the -f option. For example, this
command will start mail with the folder "projects":
mail -f projects
• While you are in the mail program, you can switch between different folders by using the
"folder" command at the "&" prompt. For example, this command switchs the current
folder to "Mail/jsmith":
folder jsmith
• If you prefer to save all of your folders to a certain subdirectory, and don't wish to type
the full name of that directory everytime you save a message or switch folders, mail
provides a feature to make this more convenient.
o Set an environment variable called "folder" to point to the directory where all of
your mail folders should be kept. For example, the following line could be added
to your .cshrc file:
o When saving or accessing a folder, precede the folder name with a "plus sign" (+).
This will tell mail to use the location specified by your "folder" environment
variable. For example:
o
o s +projects
o
o mail -f +projects
o
o folder +projects
/usr/lib/Mail.rc
Variable Action
-------- -----------------------------
alias name address - Creates an alias for a mail address
ask - Prompts for the subject of each message
sent
askcc - Prompts for carbon copy mail addresses
crt=lines - Defines the number of lines of a mail
message the Mail program displays before
pausing for input. Works with PAGER.
EDITOR=editor - Gives the full path name of the
editor to be started with the e mailbox
subcommand or the ~e mail editor
subcommand.
folder=directory - Directory to save mail files in.
hold - Keep messages that have been read in
the system mailbox, not the mbox file.
ignore fieldlist - Specifies which header fields to
not display(ignore)
keepsave - do not delete messages that have been
saved. Keep them in the system mailbox.
Use with the hold option.
nosave - Prevents retention of interrupted
letters in the $HOME/dead.letter file.
PAGER - the pager used to paginate output
when a message is longer than the
screen. Works with "crt" setting.
record=fileName - Defines a file in which to record
outgoing mail.
screen=lines - Defines the number of lines of
message headers displayed before pausing
for input.
topline=number - the number of lines of the top of each
message to print with the ~t command.
VISUAL=editor - the name of the editor called by
the ~v command. Editor is given as a
full pathname.
• A simple .mailrc file appears below. Note that more than one option can be placed on a
line.
•
• # Simple .mailrc file
• #
• set ask askcc EDITOR=/source/local/bin/pico folder=Mail
• set PAGER=more crt=20
•
Alternately, you can open pine directly into the email composer by using the command
"pine user@address". An example of pine's email composer screen appears here.
• System wide and personal configuration options can be used to tailor pine's behavior.
Your personal configuration options are specified in a file called ".pinerc" located in your
home directory.
• See the pine man page for additional details.
Introduction to UNIX
Electronic Mail Exercises
Sending Mail - Basic Example
1. Open a new window or use an existing window for this exercise. Then make sure that you are in
the Email subdirectory:
2.
3. cd ~/Email
4. Begin a mail message to yourself. You'll need to know your student userid and the name of your
classroom login machine. Your student userid is your login userid. To find your machine's name,
type the hostname command.
mail studntXX@nodeX.class.mhpcc.edu
5. When prompted for the subject, make one up and then press the Return key.
6. You are now ready to type the actual mail message. Try typing several lines.
7. When you are ready to send the message, type CTRL-D. You will be prompted to Cc: someone,
but just hit the Return key to ignore it. Your mail is immediately sent.
8. Return to the tutorial to learn about the next section before proceeding.
1. Start another mail message to yourself as before, being sure to substitute your userid for
"studntXX" and your machine name for "nodeX.class.mhpcc.edu"
2.
3. mail studntXX@nodeX.class.mhpcc.edu
4. Quitting a mail message: There will be times when you will not want to send the message after
you have started it. The ~q, typed as the very first two characters on a line will permit you to do
this. Use the ~q send mode command to quit this message.
5. Displaying help: Begin another mail message to yourself. Type in a subject and then a line or
two of actual message. Then use the ~? send mode command to display send mode help.
Remember that all send mode commands must be the first two characters on a line - otherwise,
they will just end up as part of the message text.
6. Displaying the message buffer: Type in a few more lines. Then use the ~p command to display
the progress of your message so far.
7. Changing the subject line: You may wish to change a message's subject line before you send it.
Type the following command to do this:
8.
9. ~s This is a New Subject
You may be confused and think this will become part of your mail message because it
appears to be in the message body. To prove that the command did what it was supposed
to do, use the ~p command to display the true contents of the mail message.
10. Reading in other files: Email is useful for more than just friendly correspondence. It is often
used for sending documents, data, images and even executable computer programs. These files
can be read into a mail message with the ~r command.
~r add.me
11. Writing out to other files: You can always save a mail message you are in the middle of creating
by using the ~w command. This is useful if you have to leave and can't finish the mail message
right now. If you save it, you can pick up where you left off later by reading the file into a new
mail message. Try the command below, noting that a confirmational message will display after
the file is saved.
12.
13. ~w saved.message
14. Using other editors: Let's face it, the default mail editor is not useful for more than one line
messages. You will almost always want to invoke a different editor. Try one or both of the
following.
o Invoke the vi editor:
1. Type the ~v command. Your current mail message buffer will now appear via a
vi session.
2. Do some editing.
3. When you're ready to return to mail, use the :wq command. This will exit vi and
return you to mail's send mode.
4. Use the ~p command to confirm your vi editing changes.
o Invoke the pico editor:
1. This is slightly more complicated because you must first tell mail where this
alternate editor program is installed. It will vary on different systems. At the
prompt, type the command shown below.
2.
3. ~:set EDITOR=/source/local/bin/pico
You will learn later how you can create a mail configuration file so that mail will know
where pico (or any other editor) is installed. Then you will not be required to use the
~:set command above.
15. Finish this mail file and send it to yourself by using the CTRL-D send mode command.
19. Return to the tutorial to learn about the next section before proceeding.
Reading Mail
1. Starting mail in command mode: By now, you have sent several messages to yourself. These
have been stored by the system. To read them, simply type the command mail. Your indexed list
of messages will appear.
Compare your indexed list against the tutorial's to understand the information which is
being displayed. In particular, notice the:
The & prompt is your clue that you are in mail's command mode. You are not sending or
editing messages to others - you are "doing" your own mail.
2. Reading the current message: Read the current message by typing t or pressing the Return key.
What happens? When the message is completely displayed, the & prompt will indicate that mail
is ready to receive another command.
If the message is more than one screen in length, it will probably scroll off the screen
(this is system dependent). To prevent this, you can specify a "pager" program in the mail
configuration file - which will be covered later.
3. Reading the next message: You can read the next message simply by typing n or hitting the
Return key at the mail command prompt (&). Try both. If you get to the end of your messages,
mail will tell you At EOF , which means, "At End Of File".
4. Reading any message: You can read any message simply by typing its message number at the
mail command prompt (&). Read the first message again by typing the number 1 at the mail
command prompt (&). Try the same with another message number.
5. Return to the tutorial to learn about the next section before proceeding.
1. Getting help: Type the command ? to see the command mode help.
2. Displaying the message headings: The message heading list can be displayed by typing h at the
mail command prompt (&). This is useful to know if you forget which message is which. You can
also use the f command to display message headings for a range of messages. Try these
commands:
3.
4. h
5. f
6. f *
7. f 1-2
8. Deleting messages: Delete the first message in your mailbox with the command d1. Display your
message headings with the h command to confirm that it was deleted. Note that using the d
command without a message number will delete the current message. Also, the d command
accepts a list of messages or the wildcard character (*) as arguments.
9. Undeleting messages: Undelete the previously deleted message by using the u command.
Display your message headings with the h command to confirm that it was undeleted. Note that
the u command accepts a list of messages or the wildcard character (*) as arguments.
10. Replying to messages: The r and R commands are used for this...however, since the only mail
which you've received is from yourself, you'll have to try these with real mail later. Sorry.
11. Sending a new mail message: Use the command below to send another mail message to
yourself. This will put you into mail's send mode. Create a message and then send it off. You will
see it the next time you start up mail in command mode. Don't forget to substitute your userid
and machine name as appropriate.
12.
13. m studntXX@nodeX.class.mhpcc.edu
14. Issuing UNIX commands from within mail: To issue any UNIX command from within mail, simply
preceed that command name with an exclamation mark. Try the following:
15.
16. !ls
17. !ls -l
18. !date
19. !man cp
20. Quitting mail: You can exit mail with either the x or the q commands. If you choose x, then your
previous mail box commands (such as deletes) will not be retained and your mail will be saved
as though it was unread in the system mailbox.
If you choose q, then your mail box commands will be applied and your read messages
will be placed into a file called mbox in your home directory.
Quit mail by using the q command. Check your home directory for a file called mbox. It
contains your undeleted, read mail.
Parimal Sudas Page 92
21. Return to the tutorial to learn about the next section before proceeding.
1. Understanding mbox: Mail will usually start by trying to read your system mailbox, located in a
"system" location, such as /usr/spool/mail/studntXX. This is where your new, unread mail is
kept.
Your previously read mail, however, will be kept in a file (folder) called mbox in your
home directory. Assuming that you have completed the previous exercises, you should
have several mail messages stored in the mbox folder.
Change directory to your home directory and make sure your mbox file exists:
cd
ls -l mbox
mail -f mbox
2. Saving mail messages to a folder While you are in mail's command mode, you can use the s
command to save mail to another file/folder. For example, to save the current mail message to a
new file/folder, type the command:
3.
4. s new.folder
5. Accessing other folders: The folder command can be used to access folders of mail files. Note
that folders are created by you for organizational purposes. It is up to you to remember where
you have stored things!!
Access the new.folder with the command folder new.folder It should contain the files
you saved in the previous step.
6. Returning to a folder: Now that you know that mail messages are stored in text files, you can
return to any folder simply by using the folder command. To get back to your mbox folder, type
the command below:
7.
8. folder mbox
Start up mail with your mbox folder using the command mail -f mbox
Mail provides a shorthand for saving files into folders. Since you have done the necessary
setup, you can abbreviate the folder pathname specification with a plus sign (+). Save a
couple files with the command s +dakine
Now access this folder by the mail folder shorthand: folder +dakine You should see the
mail messages you saved from the previous step.
Experiment more if you wish. When you're done, exit mail with the q command. Note
that if you list the contents of your Mail subdirectory, you will see the folder you created
above.
10. Return to the tutorial to learn about the next section before proceeding.
1. Examine your system's default mail configuration options with the command
2.
3. cat /usr/lib/Mail.rc
4. Begin an editing session and create a new file in your home directory called .mailrc - note that
it's name begins with a "dot", so that it will be a "hidden" file.
5. In your .mailrc file, specify some mail options. To begin with, you may wish to try the example
from the tutorial:
6.
7. # Simple .mailrc file
8. #
9. set ask askcc EDITOR=/source/local/bin/pico folder=Mail
10. set PAGER=more crt=20
11. Try mail now. Determine how the options in your .mailrc file affect your mail session.
12. Return to the tutorial to learn about the next section before proceeding.
1. Start pine: Make sure that you are in your home directory. Then type the command pine. Since
this is your first session, you will receive a screen full of information from pine. Read the
information carefully. Two important points to remember are mentioned:
o pine will create a subdirectory called mail in your home directory. This is where all of
your pine related mail will be kept.
o pine will automatically create a pine configuration file for you called .pinerc
2. Main Menu: After reading the opening message, press any key to continue. You should then see
the pine main menu. Take a moment to familiarize yourself with this menu.
You may also see a message about INBOX. This is what pine calls your incoming
mailbox. If you had any messages left there from the previous exercises, pine will notify
you. It will also tell you if there are none.
3. Online documentation: Pine includes an online manual. From the Main Menu, type the help
command ? to access the built in documentation. Notice the commands which appear at the
bottom of the screen. Press the space bar to see the next page. Read at least several pages of
the documentation and then type M to return to the Main Menu.
4. Compose a message: From the Main Menu, type C to begin composing a mail message. You will
immediately enter the compose screen. Notice the new commands which appear at the bottom
of the screen. In particular, notice that they are all "Control" character commands. Pine uses the
"caret" character (^) to designate CTRL. You may also recognize that these commands are
actually pico editor commands. Pine uses pico by default.
Notice that the "To:" line is highlighted. This tells you that pine is ready to have you type
in the email address of this message's recipient. Send the message to yourself, being sure
to substitute your userid for "studntXX" and your machine name for
"nodeX.class.mhpcc.edu" as you did in the previous mail exercises:
studntXX@nodeX.class.mhpcc.edu
Fill in the Subject: field and then type a couple of lines of message. When you're ready to send
the message, type the ^X command to send it. Pine will prompt you for confirmation - type y to
confirm. The message will be sent and you will be returned to the Main Menu.
Send at least three additional messages to yourself. Notice that pine will notify you
whenever a message arrives.
5. Getting help: Pine includes an excellent, context-sensitive help system. As an example, enter the
"Compose Message" screen. Move your cursor to various fields on the screen, such as the "To:"
When you're done exploring the help for the compose screen, use the ^C command to
cancel the compose and return to the Main Menu.
6. Reading your mail: Your incoming mail is kept in pine's INBOX folder. By default, this is the
current folder. From the Main Menu, view the INBOX index with the I command. You will
immediately go to the folder index screen. The messages you sent previously should be visible
now.
The current message will be highlighted. Press the Return key to read it. The message
will display, as will new command options. After reading the message, move to the next
message by typing the N command.
Try accessing the help screen by typing the ? command. Type the E command to exit
help.
You can return to your folder index when you are done reading mail messages by using
the I command. Try this. Then use the up and down arrow keys to select different mail
messages. Notice how the index changes as you read messages (the N - new message
indicator is removed after a message is read).
7. Saving mail to a folder: Pine allows you to create and use folders for organizing your mail in
much the same way as UNIX mail. Try saving a couple messages to a new folder by following the
steps below:
1. Go to the INBOX folder index screen if you are not already there
2. Select any message to save by using your up/down arrow keys to highlight the message
3. Type the S command. You will be prompted to enter the name of the folder. Type the
name new.folder
4. You should then see a message that says "Folder "new.folder" doesn't exist. Create? (y/
n) [y]:" - type y to confirm.
5. Pine will copy the message to the folder (kept in the mail subdirectory). You will then
see an informational message which says " [Message 2 copied to folder "new.folder"
and marked deleted]".
Pine assumes that once you save a message to a folder, it is no longer needed and
so, marks it for deletion. You can "undelete" the message by simply typing the U
command.
6. Save at least one other message to the same folder. Notice that since this folder now
exists, you won't see the same prompts as before.
7. Go back to the Main Menu by typing the M command.
2. Changing folders: Pine makes moving between folders very easy. Follow the steps below to see
for yourself.
Alphabetical List
Functional List
Information
Miscellaneous
Printing
Programming Tools
Terminal Related
uucp / BNU
• Script files should be given "execute" file permission with the chmod command:
•
• chmod u+x myscript
• A simple shell script which will run under any of the 5 shells appears below. This script simply
displays a greeting and the date/time. Comments are preceeded with a pound sign (#):
•
• #Simple Script
• #
• echo 'Welcome to the world of script files'
• date
Expressions
• Expressions are statements, composed of constants, variables and operators, which are
evaluated to determine a result. Expressions can be either mathematical or logical.
Example 1: Mathematical expression, where "a" and "t" are variables, "3" and "4" are
constants, and "=" and "+" are operators.
a = 3 + 4t
Example 2: Logical expression, which evaluates to either "true" or "false". The string
"exit" is a constant, "var" is a variable, and "(", ")" and "==" are operators.
($var == exit)
• Shell scripts commonly use expressions. Each shell has its own rules for writing expressions,
however.
• The C Shell recognizes the following operators, in order of precedence.
•
• () - parenthesis - change order of evaluation
• - - unary minus/negation
• ~ - one's complement
Control Structures
Script languages make use of programming control structures, such as "if" statements and "loops".
Those for C Shell are described below.
if
Used to test an expression and then conditionally execute a command. If the specified
expression evaluates true, then the single command with arguments is executed.
Command must be a simple command, not a pipeline, a command list, or a parenthesized
command list.
Syntax:
Example:
#!/bin/csh
if ($#argv == 0) echo There are no arguments
d - file is a directory
e - file exists
f - file is an ordinary file
o - user owns the file
r - user has read access to the file
w - user has write access to the file
x - user has execute access to the file
z - file is zero bytes long
if / then / else
Used to test multiple conditions and to execute more than a single command per
condition. If the specified expr is true then the commands to the first else are executed;
otherwise if expr2 is true then the commands to the second else are executed, etc. Any
number of else-if pairs are possible; only one endif is needed. The else part is likewise
optional.
The words else and endif must appear at the beginning of command lines; the if must
appear alone on its command line or immediately after an else.
Syntax:
if (expr) then
commands
else if (expr2) then
commands
else
commands
endif
Example:
#!/bin/csh
if ($#argv == 0) then
echo "No number to classify"
else if ($#argv > 0) then
foreach / end
The foreach statement is a type of loop statement. The variable name is successively set
to each member of wordlist and the sequence of commands until the matching end
statement are executed. Both foreach and end must appear alone on separate lines.
Syntax:
Example:
#!/bin/csh
foreach color (red orange yellow green blue)
echo $color
end
while / end
The while statement is another type of loop statement. Statements within the while/end
loop are conditionally executed based upon the evaluation of the expression. Both while
and end must appear alone on separate lines.
Syntax:
while (expression)
commands
Example:
#!/bin/csh
set word = "anything"
while ($word != "")
echo -n "Enter a word to check (Return to exit): "
set word = $<
if ($word != "") grep $word /usr/share/dict/words
end
break
Used to interrupt the execution of a foreach or while loop. Transfers control to the statement
after the end statement, thus terminating the loop. If there are other commands on the same line
as a break statement, they will be executed before the break occurs. Multi-level breaks are thus
possible by writing them all on one line.
Syntax:
break
Example:
#!/bin/csh
foreach number (one two three exit four)
if ($number == exit) then
echo reached an exit
break
endif
echo $number
end
continue
Used to interrupt the execution of a foreach or while loop. Transfers control to the end statement,
thus continuing the loop. If there are other commands on the same line as a continue statement,
they will be executed before the continue occurs.
Syntax:
Example:
#!/bin/csh
foreach number (one two three exit four)
if ($number == exit) then
echo reached an exit
continue
endif
echo $number
end
goto
The goto statement transfers control to the statement beginning with label:
Syntax:
goto label
Example:
#!/bin/csh
if ($#argv != 1) goto error1
if ($argv[1] < 6) goto error2
goto OK
error1:
echo "Invalid - wrong number or no arguments"
echo "Quitting"
exit 1
error2:
echo "Invalid argument - must be greater than 5"
echo "Quitting"
exit 1
OK:
echo "Argument = $argv[1]"
exit 1
The switch structure permits you to set up a series of tests and conditionally executed
commands based upon the value of a string. If none of the labels match before a `default'
label is found, then the execution begins after the default label.
Each case label and the default label must appear at the beginning of a line. The
command breaksw causes execution to continue after the endsw. Otherwise control may
fall through case labels and default labels. If no label matches and there is no default,
execution continues after the endsw.
Syntax:
switch (string)
case str1:
commands
breaksw
case str2:
commands
breaksw
...
default:
commands
breaksw
endsw
Example:
#!/bin/csh
if ($#argv == 0 ) then
echo "No arguments supplied...exiting"
exit 1
else
switch ($argv[1])
case [yY][eE][sS]:
echo Argument one is yes.
breaksw
case [nN][oO]:
echo Argument one is no.
breaksw
default:
echo Argument one is neither yes nor no.
breaksw
endsw
endif
The onintr statement transfers control when you interrupt (CTRL-C) the shell script. Control is
transferred to the statement beginning with label:
Can be useful for gracefully cleaning up temporary files and exiting a program should it be
interrupted.
Syntax:
onintr label
Example:
#!/bin/csh
onintr close
while (1 == 1)
echo Program is running
sleep 2
end
close:
echo End of program
Miscellaneous
Miscellaneous tasks for C Shell programming are described below.
Using quotes
The shell uses both single (') quotes and double (") quotes. They have different effects.
Single quotes:
Double quotes:
#!/bin/csh
set opt=-l
set x1='ls $opt'
echo $x1
set x2="ls $opt"
echo $x2
#!/bin/csh
set ls1='some files: [a-z]*'
echo $ls1
The shell uses backquotes to obtain the output of the command enclosed within the backquotes.
This output can be stored within an array variable. Each element can then be indexed and
processed as required.
Syntax:
Example:
#!/bin/csh
set date_fields=`date`
echo $date_fields
echo $date_fields[1]
echo $date_fields[2]
foreach field(`date`)
echo $field
end
Sample output:
Depending on your system, you can use either "$<" or the output of the "head -1" command to
read stdin into a variable. Note that if you use the "head -1" command, it must be enclosed in
backquotes.
Note: Be careful on making sure that you use "$<" and not "<$". The latter case will usually
cause your script to fail.
Syntax:
Example:
#!/bin/csh
echo -n Input your value:
set input = $<
echo You entered: $input
- or -
#!/bin/csh
echo -n Input your value:
set input = `head -1`
echo You entered: $input
Introduction to UNIX
Shell Script Exercises
1. Open a new window or use an existing window. Change directory to the Scripts exercise
directory:
2.
3. cd ~/Scripts
4. Edit a new file - call it simple. Include the following lines in your simple file:
5.
6. #!/bin/csh
7. #
8. #Simple Script
9. #
10. echo Welcome to the world of script files
11. echo -n "The current time and date are: "
12. date
13. Make this file world executable. Check its permissions to make sure:
14.
15. chmod a+x simple
16. ls -l simple
17. Execute the file by invoking its name: simple. Observe the output. How does the -n option
modify the output from echo?
18. Return to the tutorial to learn about the next section before proceeding.
Expressions
1. Display the file simple.2 which is already provided for you in your ~/Scripts directory. Note the
use of a couple simple expressions.
2. Check to make sure the file is executable. If it isn't, then use the chmod to make it executable at
least by you.
3.
4. ls -l simple.2
5. chmod u+x
6. Execute the example file by invoking its name: simple.2 and observe the output.
7. Now, edit the file and add the lines below. When finished, save the file and try executing it
again.
8.
9. @ count = 1
10. echo Count begins as $count
11. @ count = $count + 100
13. Return to the tutorial to learn about the next section before proceeding.
if
6. After saving the file, make it executable and then run it as shown:
7.
8. chmod +x simple.3
9. simple.3
10. Now try running it several more times, but with a different number of arguments each time. For
example:
11.
12. simple.3 one two
13. simple.3 a b c 3 4
14. simple.3 9*3 65 100.34 - will cause an error - why?
15. simple.3 '9*3' 65 100.34
16. simple.3 '10 disc write' - why is this considered 1?
21. Now execute the file with a filename as the only argument and observe the output:
22.
23. simple.3 nosuchfile
24. simple.3 simple.3
25. simple.3 simple
26. Return to the tutorial to learn about the next section before proceeding.
1. Display the file simple.4 which is already provided for you in your ~/Scripts directory. It is the
same as the one from the tutorial. Attempt to understand what the expressions are evaluating
and the logic of the if-then-else nesting.
2. Make sure the file is executable (you know how to do this by now) and then try running it with
different arguments. Compare the output with the script's logic as you understand it. Do they
agree?
3.
4. simple.4 34
5. simple.4 199
6. simple.4 1000
7. simple.4 -33
8. simple.4
9. Return to the tutorial to learn about the next section before proceeding.
foreach
1. Display the file simple.5 which is already provided for you in your ~/Scripts directory.
Understand what it does and its use of the foreach construct.
2. Make sure the file is executable (you know how to do this by now) and execute it. Does it
correctly determine your login machine?
while
1. Now create your own executable script by copying the while loop example from the tutorial. It is
reproduced below for convenience:
2.
3. #!/bin/csh
4. set word = "anything"
5. while ($word != "")
6. echo -n "Enter a word to check (Return to exit): "
7. set word = $<
8. if ($word != "") grep $word /usr/share/dict/words
9. end
10. Give it execute permission and then run it. What does it do?
11. Return to the tutorial to learn about the next section before proceeding.
1. Display the file simple.6 which is already provided for you in your ~/Scripts directory. This file is
a little lengthier than previous files. Notice the use of the switch construct.
talk
• The talk command allows two users on the same host or on different hosts to have an
interactive conversation.
• The talk command opens both a send window and a receive window on each user's
display. Each user is then able to type into the send window while the talk command
displays what the other user is typing.
• A sample talk screen is available here.
• Using the talk command - some examples:
•
• talk kellyk - talk to a local user
• talk dale@wave.com - talk to a remote user
finger
• The finger command displays information about users on a given host. The host can be
either local or remote.
• Example 1: Show who is logged onto the system
• If you create a .plan and/or .project file in your home directory and make them world
readable, they will appear in the Plan and Project fields of the finger output.
• Finger may be disabled on other systems for security reasons.
• See the finger man page for details.
ping
• The ping command sends an echo request to a network host. It is useful for:
o Determining the status of the network and various foreign hosts.
o Tracking and isolating hardware and software problems.
o Testing, measuring, and managing networks.
• The ping command sends one datagram per second and prints one line of output for every
response received. Round-trip times and packet loss statistics are calculated and
displayed.
• Example:
• % ping kanaha
• PING kanaha.mhpcc.edu: (164.122.27.33): 56 data bytes
• 64 bytes from 164.122.27.33: icmp_seq=0 ttl=254 time=3 ms
• 64 bytes from 164.122.27.33: icmp_seq=1 ttl=254 time=2 ms
• 64 bytes from 164.122.27.33: icmp_seq=2 ttl=254 time=2 ms
• 64 bytes from 164.122.27.33: icmp_seq=3 ttl=254 time=2 ms
• 64 bytes from 164.122.27.33: icmp_seq=4 ttl=254 time=2 ms
• 64 bytes from 164.122.27.33: icmp_seq=5 ttl=254 time=2 ms
• ^C
• ----kanaha.mhpcc.edu PING Statistics----
• 6 packets transmitted, 6 packets received, 0% packet loss
• round-trip min/avg/max = 2/2/3 ms
traceroute
• The traceroute command prints the route that IP packets take to a network host. It is
intended for use in network testing, measurement, and management.
• Example:
• % traceroute archie.rutgers.edu
• traceroute to dorm.Rutgers.EDU (128.6.18.15), 30 hops max, 40 byte
packets
• 1 B2_IGSL_01 (129.24.96.1) 2 ms 2 ms 2 ms
• 2 FZ00_rtr_01 (129.24.56.1) 3 ms 2 ms 7 ms
• 3 msh (129.24.8.193) 5 ms 7 ms 4 ms
• 4 198.83.5.5 (198.83.5.5) 7 ms 4 ms 7 ms
• 5 hssi3-0.cnss116.Albuquerque.t3.ans.net (192.103.74.41) 5 ms 4 ms
6 ms
• 6 mf-0.cnss112.Albuquerque.t3.ans.net (140.222.112.222) 4 ms 4 ms
4 ms
• 7 t3-0.cnss64.Houston.t3.ans.net (140.222.64.1) 30 ms 30 ms 30 ms
• 8 t3-0.cnss80.St-Louis.t3.ans.net (140.222.80.1) 47 ms 47 ms 46 ms
• 9 t3-1.cnss25.Chicago.t3.ans.net (140.222.25.2) 54 ms 52 ms 53 ms
• 10 t3-0.cnss40.Cleveland.t3.ans.net (140.222.40.1) 60 ms 59 ms 59 ms
• 11 t3-1.cnss48.Hartford.t3.ans.net (140.222.48.2) 73 ms 78 ms 74 ms
• 12 t3-2.cnss32.New-York.t3.ans.net (140.222.32.3) 78 ms 76 ms 76 ms
• 13 t3-0.enss137.t3.ans.net (140.222.137.1) 79 ms 80 ms 86 ms
• 14 fenchurch-gateway.jvnc.net (192.12.211.65) 83 ms 80 ms 84 ms
• 15 airport2-gateway.jvnc.net (130.94.9.250) 84 ms 86 ms 88 ms
• 16 airport1-gateway.jvnc.net (130.94.7.1) 85 ms 92 ms 84 ms
• 17 rutgers-gateway.jvnc.net (130.94.7.10) 89 ms 86 ms 90 ms
• 18 rucs-gw.rutgers.edu (128.6.21.7) 94 ms 104 ms 95 ms
• 19 dorm.rutgers.edu (128.6.18.15) 92 ms 93 ms 91 ms
• Warning: Because of the load traceroute imposes on the network, the traceroute
command should not be used during normal operations or from automated scripts.
• The traceroute utility may not be available on all systems.
• See the traceroute man page for details.
ftp
• ftp stands for File Transfer Protocol. File transfer provides a means for you to obtain
computer files (text, image, sound, etc.) from other computers over the network.
• Many computers on the Internet permit anonymous ftp . You can login to these machines
without a real account, to obtain files which have been made publicly available.
Typically, the user name anonymous is used, coupled with your email address as the
password.
• Anonymous ftp is usually restricted so that users can only see what the server permits
them to see. Anonymous users do not have full privileges as would a user with a real
computer account.
• See the ftp man page for details.
• Begin the ftp exercise.
telnet
• Telnet is a utility that allows a computer user at one site to make a connection, login and
then conduct work on a computer at another site. For example, you can use the telnet
command to run a program in your directory on a supercomputer thousands of miles
away.
• Telnet is used to access many of the Internet resources, such as databases, libraries and
computers
• Example telnet session:
• % telnet makena
• Trying...
• Connected to makena.mhpcc.edu.
• Escape character is '^]'.
•
•
• AIX Version 3
• (C) Copyrights by IBM and by others 1982, 1993.
• login: jsmith
• jsmith's Password:
• ***********************************************************************
***
• *
*
• *
*
• * WELCOME TO THE Maui High Performance Computing Center *
• *
*
• *
*
rlogin
rsh
rcp
• rlogin (remote login), rsh (remote shell) and rcp (remote copy) are three utilities which
allow you to perform tasks on other machines without requiring the usual login
authentication.
• All three utilities depend upon a .rhosts located in your home directory. The .rhosts file
contains the names of your "trusted" hosts and your userid on each of those hosts. An
example appears below:
•
• apache.unm.edu jsmith
• zeus.mit.edu jsmith
• athena.com smith
• fox.eeco.org smithj
• rlogin: Allows you to login to a remote machine. It is nearly identical to telnet in function
and appearance, however if your .rhosts file is setup accordingly, you will be able to
login to your account on another machine wihout having to enter a userid and password.
• rsh: The remote shell command can be used to execute a command on remote host or log
into remote host. With the proper .rhosts file, authentication is not required.
• Examples:
•
• rsh host2 - will connect to host2 for
• login
• rsh host2 df - check the amount of free
• disk space on remote host2
• rcp: Remote copy enables you to copy files between different systems. With the proper
.rhosts file, authentication is not required.
• Example:
•
• rcp localfile host2:/home/eng/journal
Introduction to UNIX
Network Related Utilities Exercises
ftp
Anonymous FTP will be used to connect to an Internet computer which contains an image file
representing a Van Gogh painting. The file will first be downloaded and then an image viewing utility will
be used to display the image file on your screen.
1. Create a new window or use an existing window. Type the following command in that window:
2.
3. ftp kanaha.mhpcc.edu
4. As the network connection is established with the server computer you will see several
messages appear on your screen. You will then be prompted to enter your Name. Type the
name anonymous and hit return.
5. You will then be prompted to enter a Password. Type the password guest . You will then see a
couple messages. At the bottom of the screen, you should see the prompt: ftp> . This means
that ftp is now ready to accept commands from you.
6. View the top level file directory by typing the command: dir . This shows a typical UNIX long
directory listing. The important column is the last one on the right which shows the file names.
The ls command can also be used to give a short directory listing.
7. Change directory to the pub subdirectory, list the files, and then change to the Misc
subdirectory and list its contents by using the following commands:
8.
9. cd pub
13. You should see a file called starry.night.gif . If you do, you are now ready to download the file.
Use the command:
14.
15. get starry.night.gif
When the download is complete you will see a message that looks something like this:
20. When you are done viewing your image, left-click on the image with your mouse and then type
the letter Q for quit.
21. This completes the FTP exercise. Return to the tutorial to learn about the next section before
proceeding.
telnet
The telnet utility will be used to connect to another machine and login.
1. Create a new window or use an existing window. Type the following command in that
window, substituting a classroom machine name for nodeXX (node1-node16). Please
use a machine other than the one you are currently logged into.
2.
3. telnet nodeXX.class.mhpcc.edu
4. You will be asked to login - use your assigned userid and password. Be sure to type n
when asked to start mosaic.
If you had an account on a non-MHPCC machine, your files there would local to
that system.
6. Use logout or exit to quit this telnet session and return to your original login machine.
7. This completes the telnet exercise. Return to the tutorial to learn about the next section
before proceeding.
This exercise will familiarize you with the remote login, remote copy and remote shell
commands.
1. Create a new window or use an existing window. Make sure that you are in your
home directory by typing the cd command.
2. Use an editor to open a file called .rhosts and add the following lines to this file,
being sure to substitute your student userid for "myuserid".
HINTS: You can type in all 16 lines if you want, OR, you could:
Read in the file ~/Scripts/node.names and just add your userid to each
line
Use your editor's "cut and paste" capabilities. Just type one line and
then cut and paste it 15 times. All you'll need to change then are the
line numbers.
If you know how to use the mouse for cutting and pasting between
windows, it's even easier. Just cut from this window and paste into the
window which contains your editing session. Then change the
"myuserid" on each line.
node1.class.mhpcc.edu myuserid
node2.class.mhpcc.edu myuserid
node3.class.mhpcc.edu myuserid
node4.class.mhpcc.edu myuserid
node5.class.mhpcc.edu myuserid
node6.class.mhpcc.edu myuserid
node7.class.mhpcc.edu myuserid
node8.class.mhpcc.edu myuserid
node9.class.mhpcc.edu myuserid
node10.class.mhpcc.edu myuserid
Remote login
7. Think of a machine other than the one you are logged into (node1-node16).
8. Then, use the remote login command to automatically login to the machine you
picked. For example:
9.
10. rlogin nodeXX.class.mhpcc.edu
You will notice that you are able to login without entering a userid or password.
Be sure to type n when asked to start mosaic.
Remote copy
12. Think of a machine other than the one you are logged into (node1-node16).
13. Use the remote copy utility to copy one of your files to another machine's
temporary filespace. An example of what you might do appears below. Be sure
to substitute your chosen machine for "nodeXX" and your student userid for
"studntXX".
14.
15. rcp ~/Editors/maui.txt
nodeXX.class.mhpcc.edu:/tmp/studntXX.maui.txt
16. You will verify that the copy actually took place with a remote shell command in
the next exercise.
Remote shell
17. Using the same machine as you did for the remote copy command, remote shell
to that machine and list the contents of its temporary directory:
18.
Parimal Sudas Page 128
19. rsh nodeXX.class.mhpcc.edu ls -l /tmp
20. You should see the file you copied from the remote copy exercise.
21. Now, use rsh to remove that file - don't forget to substitute your userid for
"studntXX":
22.
23. rsh nodeXX.class.mhpcc.edu rm
/tmp/studntXX.maui.txt
24. Finally, use the remote shell command to look at all of the other machine's
student processes:
25.
26. rsh nodeXX.class.mhpcc.edu ps aux | grep studnt
What is X Windows?
• The X Window System is a network based graphical windowing system for workstations.
It was developed by MIT and has been adopted as an industry standard.
• X is supported by a consortium of industry leaders such as DEC, Sun, IBM, Hewlett-
Packard and AT&T. They have united to direct, contribute and fund the continuing
development of X.
• Most UNIX machines include X as part of their operating system. If you have "windows"
on your screen, chances are, you are using X, whether you are aware of it or not. It is
simply "part of your environment".
• The X Window System design is based upon the client-server model:
o Client: an application program which performs a specific task. For example, three
common X clients (xclock, xcalc, xterm) appear below:
o Some systems will start the X server for you automatically and provide you with
an initial login window. This is probably the case if you see a login screen that
looks something like the one below:
o Some systems require you to start the X server manually. This is usually done
with the "xinit" command. After logging in, you just type the command and let
the server do the rest.
After the server has started, you will see at least one xterm, and perhaps a couple
other xclients (clock, calculator, etc) too. This will depend upon your local
system.
o You can tailor the manner in which the X server starts by creating a file called
.xinitrc in your home directory. A sample .xinitrc from an IBM AIX system is
provided HERE.
U Starting the window manager.
o The easiest way to tell if a window manager is running is to look for a "border"
around your X clients. For example, an xclock with and without a border appears
below:
o If you need to start the window manager manually, simply type its name and put
the process in the background. For example, to start the Motif Window Manager:
mwm &
You may also be able to add a command as the last line of your .xinitrc file to
automatically start the window manager when you start the X server. For
example, to start the Motif Window Manager:
exec mwm
o After starting the window manager, your X clients will have borders and be able
to be controlled (move, resize, iconify, etc) via your keyboard and mouse.
U Starting the first xterm terminal emulator
o A terminal emulator is an X client that looks like a rectangular window and acts
as a terminal screen. It accepts input from you and will also display program
output. Most of the work you do will be done inside an xterm window.
o The most common terminal emulator xclient is called xterm.
xterm &
xhost +othermachine
2. Start the X client on the other machine. This can be done at least three
different ways:
1. Use the rsh command and include the -display option. For
example, the following command will start an xterm on machine
kanaha and send the display back to machine makena. Note that in
most cases, the display machine name must be suffixed with ":0".
2. Login to the other machine and start the X client there after you set
the DISPLAY environment variable to point to your local machine.
Again note that the display machine name must be suffixed with
":0".
3.
4. telnet kanaha
5. { enter userid and password }
6. setenv DISPLAY makena:0 &
7. xterm &
8. Login to the other machine and start the X client there using the
-display option to point to your local machine.
9.
10. telnet kanaha
11. { enter userid and password }
12. xterm -display makena:0 &
• Root Menu
o The Root Menu provides a pop-up list of the basic window manager functions.
Some of these functions include:
o
o New Window - open a new xterm
o Resize - resize window
o Move - move window
o Lower - put window below other windows
o Raise - put window above other windows
o Shuffle Up - raise window one level
o Shuffle Down - lower window one level
o Refresh - refresh window
o Clients - pop-up list of X clients
o Restart - restart the window manager
o Quit - quit the window manager
oThe Root Menu will appear if you press and hold the right mouse button. Make
sure that the pointer is not pointing on an X client - it should be pointing to an
open area on the screen.
o You can select a function from the Root Menu by holding the mouse button and
sliding the pointer until the desired function is highlighted/raised. Releasing the
mouse button will select the function.
• Window Frame
o The window frame surrounds the X client and consists of
title area
minimize button
maximize button
window menu button
four sides
four corners
Also selected window functions (move, resize, lower, etc) can be displayed by
placing the mouse cursor on the title bar and holding down the middle mouse
button.
o Minimize button: Located in the upper right hand corner. To turn the window into
an icon (an icon is a small image), click the left mouse button on the Minimize
button
o Maximize button: Located in the upper right hand corner. To make the window
fill the screen click the left mouse button on the Maximize button
o Window Menu button: Located in the upper left hand corner. To pull down the
window menu, place the pointer over the button and press the left mouse button.
While pressing the button, drag the pointer on the menu to your selection and
release the button when your selection is highlighted.
o Sides and Corners: Any of the four sides or corners can be used to resize the
window. Simply place the pointer over the frame component and press the left
mouse button. While holding the button, drag the pointer in the desired direction.
A wire frame is moved during the drag to indicate the new size. When the button
is released, the window is resized.
• Special Keys
o Special keys may also be used in combination with the mouse buttons. For
example:
o
o ALT + left button - lower window
o ALT + middle button - resize window
o ALT + right button - move window
o CTRL + left button - xterm client: options menu
o CTRL + middle button - xterm client: vt options
o CTRL + right button - xterm client: vt fonts
• In order to do further customization via an .Xdefaults file, you need to know the actual
resource specification. These are unique for each X client. An example .Xdefaults file can
be viewed here.
• Colors
o Many X clients allow you to alter their default colors. The colors available to you
will depend upon your system, but can usually be found by reviewing the file:
/usr/lib/X11/rgb.txt
o X client colors can often be set with command line options. In the example below,
an xterm is created with a blue background and white foreground (text):
o For more detailed (and permanent) color specifications, the .Xdefaults file can be
used. For example, the following lines might be used to set xterm colors:
o
o xterm*background: DarkSlateBlue
o xterm*foreground: LemonChiffon
o xterm*cursorColor: red
o xterm*pointerColor: red
o Although it is usually easiest to just use the color name, colors can also be
specified in hexidecimal format. This may be useful if you need a color that isn't
available on the system by name:
o
o #000000 black
o #FF0000 red
o #00FF00 green
o #0000FF blue
o #00FFFF cyan
o #5F9F9F cadet blue
• Fonts
o Many X clients permit you to specify alternate font(s) for text. The fonts which
are available to you depend upon your system, but they can usually be found by
reviewing the file: /usr/lib/X11/fonts/fonts.dir.
You can also use the xlsfonts utility to list all of your system's available fonts.
o Full font specifications are very detailed. Wildcards (*) can also be used. For
example:
•
o The xfd utility is helpful for viewing a font before you actually use it. For
example:
• Geometry
o All X clients that display in a window allow you to specify their size and location
on the screen by using the geometry option:
o The syntax is:
o
o -geometry width x height +/- xoffset +/- yoffset
o
o width = in pixels usually; in characters for xterm
o height = in pixels usually; in rows for xterm
o +xoffset = pixels from left edge of screen
o -xoffset = pixels from right edge of screen
o Example 1: Creates an xclock 125 pixels wide by 125 pixels high and places it 10
pixels from the right edge of the screen and 20 pixels from the top of the screen.