Using UNIX: Advanced Topics Part 2
Description:
The "UsingUNIX Guide" is available for download to read or print inPDF format. If you choose to print this document in an ACS lab, print in rangesof 20 pages (print pages 1-20, 21-40, 41-60, etc.) To view this document on theweb, follow a link below.
Table of Contents
- Conventions
- Using the vi Editor
- Understanding Foreground and Background Processing
- Miscellaneous Commands
- Shell and Environment Variables
- Using X Windows With a Workstation
Using the vi Editor
vi is a full-view lineeditor. You use vi to create and modify your programs and documents when youwork on a UNIX-based system. There are several ways to start the vi editor, asdemonstrated below.
vi-- will invoke the editor, without opening a file
vi filename-- will invoke the editor, and open the file or create the file if it does notexist
vi /directory/filename-- will invoke the editor, and open/create the file
Operating Modes in the vi Editor
Text Input Mode
vi has two text input modes,append and insert. Typing
a,from command mode, will put you in append mode (text will be added behind thecursor). Typing
i, fromcommand mode, will put you in insert mode (text will be added before thecursor).
Command Mode
All vi commands must beentered from command mode. When the vi editor is started, you are automaticallyplaced in command mode. To get to command mode from text input mode, press
<esc>. If you hear abeep when you press
<esc>,you are already in command mode. Note, vi commands are case sensitive - typeuppercase and lowercase characters as such.
When you press
<esc> nothing appears on thescreen.
Aborting Commands
To abort a command you canpress
<esc>. If youabort a command, you will still be in command mode.
In addition to pressing
<esc>, you can type
u (from command mode)to reverse the effect of the last command that changed the buffer. If you type
U (from command mode),the effect of all the commands on the current line will be reversed, providedyou have not moved from the line since the last change.
Also, you can correct typingerrors from either of the text input modes by pressing the backspace key andtyping over the incorrect text.
Saving Files
There are several ways tosave files in vi, some of them are illustrated below.
:
wq or
ZZ or
:x
writesbuffer to file, and exits vi
:w
writesbuffer to file, and stays in vi
:q
exitsvi without saving changes
:w
filename
writesbuffer to filename (will not write to an existing file)
:w!
filename
writesbuffer to filename (overwrites existing file)
:q!
exitsvi, and aborts all changes
Cursor command
vi has many ways of movingthe cursor around in a document. Normally, the arrow keys on your keyboard willwork, as long as you are in command mode. However, if you find that the arrowkeys are not functioning properly you can choose any of the following commands.
h
movesone character left, within current line
l
movesone character right, within current line
j
movesdown one line
k
movesup one line
b
movesleft to beginning of next word, or punctuation mark
B
movesleft to beginning of next word, ignoring punctuation
w
movesright to beginning of next word, or punctuation mark
W
movesright to beginning of next word, ignoring punctuation
<ctrl-f>
scrolls forward one full screen
<ctrl-b>
scrolls backward one full screen
<ctrl-d>
scrolls forward one-half page
<ctrl-u>
scrolls backward one-half page
H
movescursor to top left of screen
M
movescursor to middle left of screen
L
movescursor to bottom left of screen
G
movescursor to the beginning of the last line of file/document
In addition to the commandslisted above, you can add numbers to the front of the command to make it performits function multiple times. For example, typing 6b will move the cursor backsix words.
Delete Commands
Below are just a few of thecommands you can use to delete characters, words, or lines.
x
deletes character at the cursor position
dd
deletes current line
dw
deletes one word right
You can prefix the deletioncommands with numbers to process multiple functions simultaneously. For example,typing
2dd will deletethe next two lines.
Insert Commands
With vi you can insert textand/or blank lines. To enter text, issue one of the following commands. Rememberto press
<esc>, toreturn to command mode.
i
putsyou in insert mode, insertion occurs before the current cursor position
I
movescursor to beginning of current line, and enters insert mode
o
creates a blank line following the current line, moves the cursor to thebeginning of the new line, and enters insert mode
O
creates a blank line before the current line, moves the cursor to the beginningof the new line, and enters insert mode
a
putsyou in append mode, text will be added after current cursor position
A
movescursor to end of current line, and enters append mode
Search Commands
You can use the searchcommand to help you locate a text string. If you want a match for just thecharacters entered as the string, be sure to include a space preceding andfollowing the string.
/string
searches forward from cursor position for string
?string
searches backward from the cursor position for string
n
repeats search in same direction
N
repeats search in opposite direction
If you want to find alloccurrences of the word ear. Enter the command "
/ear ". If you type "
/ear",you will find all occurrences of the word ear, and also fear, earth, bear, etc.
Change Commands
vi has several commands thatallow you to change characters, words, and lines. Some of the commands anddescriptions are below.
r
allowsyou to replace one character at current cursor position
cw
allowsyou to replace one word at current cursor position
ct
x
allowsyou to replace text from current cursor position to a specified character
x
xp
transposes the letter at the cursor position with the following letter
ddp
swapsposition of the current line and the following line
R
allowsyou to replace all characters beginning at the cursor position; at end of line,editor enters insert mode
You can prefix r and cw withnumbers to make multiple changes.
Paste Command
When a string is deleted itis stored in a temporary buffer. Deleted text stays in this buffer until youmodify the buffer by deleting another string or exit the editor. The textstrings stored in this buffer can be removed and placed back in the text. Thiscan be done by using the commands below.
p
placeslast deleted text following the cursor
P
placeslast deleted text before the cursor
Marking Text
To make a bookmark in adocument place the cursor at the location where you want the bookmark; type
m
x(where
x is anyletter you choose to symbolize that particular bookmark). To return to themarked position type
`
x(grave accent {backward single quote} followed by the character
x you specified). Typing
'
x(apostrophe {forward single quote} followed by the character
x you specified), willreturn you to the beginning of the line that contains the mark. You can havemore than one bookmark in a file. Marks are forgotten when you exit vi or closethat document.
Moving Marked Text
You can delete the textbetween your mark and the current cursor position by typing
d`
x(backward single quote). Then, you can move the cursor to where you want to addthe text, and type
p or
P.
Yank Command
The
yank command copies text into atemporary buffer. It does not change the original text when it makes the copy.Text remains in the buffer until you enter another command that places text intothe buffer, or exit the editor.
Your original text is notdeleted, just copied.
yy or Y
copiesthe line at the cursor into the buffer
nyy or nY
copies
n lines fromthe cursor position into the buffer
yw
copiesthe word at the cursor into the buffer
nyw
copies
n wordsfollowing the cursor position into the buffer
Copying Yanked Text
You can use the
yank command with the pastecommand to copy text to another location in the current document.
Reading Other Files Into Current File
You can insert another fileinto the current file by typing
:r
filename.The inserted file will be added starting on the line following the cursorposition.
Repeating Commands
If you type a period
(.), the last command thatmodified the buffer will be repeated. You can use this instead of having toretype commands.
Joining Lines
Typing
J allows you to join thecurrent line and the following line. Typing
n
J will join
n lines tothe current line.
Understanding Foreground and Background Processing
UNIX systems are multitaskingsystems. This means that you can run more than one process at the same time. Aprocess can be anything from listing the contents of a directory to running aprogram.
A foreground process is anytask that you run on your terminal you'll return to the command prompt only whenyou complete your entire task. You may have only one foreground process runningat any time. You can suspend a foreground process by pressing
<ctrl-z>. After suspending aforeground process, you return immediately to the command prompt.
To run multiple processes ona UNIX system, you must run them in the background. A process running in thebackground is called a background job. Background jobs should not require yourintervention. You can run several background jobs simultaneously you arenotified when a background job is completed.
Running a Background Job
The nice Command
The jobs Command
The fg Command
The stop Command
The kill Command
To run a process as abackground job, follow the command for that process with an ampersand
(&). The job is then assigned ajob number and a unique process identification number (PID). After starting ajob in the background, you'll return to the system prompt where you can executeother commands or start other jobs.
A trade off exists betweenrunning several jobs in the background simultaneously and the system response.Running several jobs in the background can significantly degrade the interactiveresponse you receive on a UNIX system.
The nice Command
When running a process as abackground job, you should precede the command for that process with the
nice command. The format of the
nice command used torun a process as a background job is:
nice [-n] command [options]&
where
n is an optional numberbetween 1 and 20, command is the command for that process, and options are anyoptional arguments for that command. The optional number included after the nicecommand determines the priority level of the background job the lower thenumber, the greater the priority. If you do not include a number with the
nice command, 10 isused as the default.
If you want to be able tologout of your account and have a job continue to run in background, precede theprevious command by the word
nohup. The previous command would become:
nohup nice [-n] command [options]&
In the following example, the
nice command is usedwith the FORTRAN compiler command, f77, at a nice level of 20; the object of thecompiler command is the FORTRAN program called random.f (for information oncompilers, please see "Running Programs on UNIX"; for information on the jobscommand, see "The jobs Command"):
%
nice -20 f77 random.f & <return>
[1] 20394
%
jobs <return>
[1] + Running f77 random.f
%
The jobs Command
The
jobs command displays thestatus of any background jobs. The format of the
jobs command is simply:
jobs
In the following example, the
jobs command displaysthe single background job running:
%
jobs <return>
[1] + Running f77 random.f
%
If you have used the
nohup command to run a job inbackground and then logged out of your account, issuing the
jobs command after you log backin will not show the status of that job. To see its status, enter the followingcommand:
ps auxww | grep
userid
If the job is still running,its status will be shown. If the job has completed, it will not appear.
The fg Command
The
fg (foreground) command returnsa background job to the foreground. The format of the
fg command is:
fg %
n
where
n is the job number. If the
fg command is usedwithout any objects, the most current job in the job list is brought into theforeground.
The stop Command
The
stop command stops a jobcurrently running in the background. The format of the
stop command is:
stop % n where n is the job number.
The kill Command
The kill command cancels a jobrunning in the background. The format of the kill command is: kill %
n
or
kill -9 %
n
where
n is the job number. Specifyingthe -9 option with the
kill command kills the process under all circumstances.
The following examplesillustrate the concept of running jobs in the foreground and background:
%
more file1 <return>
This is line number 1
This is line number 2
.
.
.
--More--(57%)
<ctrl-z>
Suspended
%
ls -l <return>
total 8
-rw------- 1 jsmith 1865 Nov 19 12:00file1
-rw-rw---- 1 jsmith 256 Nov 01 09:05file2
-rw----rw- 1 jsmith 865 Dec 25 05:00file3
drw-rw---- 2 jsmith 512 May12 11:23letters
<ctrl-z>
Suspended
%
cat file1 file2 > file3 & <return>
[3] 5421
%
jobs <return>
[1] Suspended more file1
[2] - Suspended ls -l
[3] + Running cat file1 file2 > file3
%
diff file1 file2 > file.dif &<return>
[4] 5427
%
The first number representsthe job number and the second number is the unique process identification number(PID) assigned to the job.
%
jobs <return>
[1] Suspended more file1
[2] Suspended ls -l
[3] - Running cat file1 file2 > file3
[4] + Running diff file1 file2 > file.dif
%
[3] Done cat file1 file2 > file3
%
As shown in the aboveexample, you are informed when any background job finishes.
%
jobs <return>
[1] Suspended more file1
[2] - Suspended ls -l
[4] + Running diff file1 file2 > file.dif
%
fg %1 <return>
more file1
This is line number 1
This is line number 2
.
.
.q
%
kill %2 <return>
[2] Terminated ls -l
%
kill %4 <return>
[4] Terminated diff file1 file2 > file.dif
%
jobs <return>
%
If you try logging out andyou have any stopped jobs, you are notified by the system of those jobs. If youdo not need the stopped jobs, you should kill them. In either case, you can usethe logout command or
<ctrl-d> a second time to log out.
Miscellaneous Commands
The history Command
The alias Command
The cal Command
The date Command
The who Command
The quota Command
The limit Command
The history Command
The
history command displays thelast 20 commands used (by default), but this number can be increased ordecreased.
You can reissue a previouscommand with one of the following commands:
!!-- Execute the last command entered.
!
n
-- Execute command number
n on the history list.
!
xxx-- Execute the most recent command on the history list starting with xxx.
!-n-- Execute the nth command ago.
The following example showsthe history command being used:
% history <return>
1 more file1
2 pwd
3 cd /
4 cd
5 history
% !2 <return>
pwd
/home/dept/jsmith
% history <return>
1 more file1
2 pwd
3 cd /
4 cd
5 history
6 pwd
7 history
% !-7 <return>
more file1
This is line number 1
This is line number 2
.
.
.q
% history <return>
1 more file1
2 pwd
3 cd /
4 cd
5 history
6 pwd
7 history
8 more file1
9 history
% !c <return>
cd
% pwd <return>
/home/dept/jsmith
%
The alias Command
The alias command is used formaking a nickname or abbreviation for a UNIX command. You can consequentlydesignate your own name for any UNIX command. The format of the alias command is:
alias nicknameUNIX_command
To display a list of allcurrent aliases, use the alias command with no object. In the following example, the alias command is used first tonickname the more command as type and then the ls command, including the -l(long) option, as long:
% alias type more <return>
% alias long 'ls -l' <return>
% type file1 <return>
This is line number 1
This is line number 2
.
.
.q
% long <return>
total 8
-rw------- 1 jsmith 1865 Nov 19 12:00file1
-rw-rw---- 1 jsmith 256 Nov 01 09:05file2
-rw----rw- 1 jsmith 865 Dec 25 05:00file3
drw-rw---- 2 jsmith 512 May12 11:23letters
% alias <return>
type more
long ls -l
%
The cal Command
The cal (calendar) command displaysthe calendar for the specified month and year. The format of the cal command is:
cal month year
If you exclude the monthnumber from the cal command, the calendar for the entire specified year is displayed.
% cal 4 1992 <return>
April 1992
S M Tu W Th F S
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
%
You must specify the entireyear with the cal command. For example, cal 90 displays the calendar for 90 AD, not 1990. Todisplay the calendar for 1990, you must use cal 1990. The cal command with no objectdisplays the calendar for the current month.
The date Command
The date command displays thecurrent date and time on your screen:
% date <return>
Thu Aug 28 08:56:28 CDT 1997
%
The who Command
The who command displays all userscurrently logged in to a UNIX system. The who command displays the user'slogin name, the device to which the user's terminal is connected, and the logintime and date.
In the following example, thewho command shows threeusers currently logged in:
% who <return>
opr5 console Aug 20 07:54
jsmith ttyp0 Aug 20 09:38 (129.107.1.100)
bcarson ttyp3 Aug 20 10:43 (129.107.1.100)
The quota Command
The quota command displays the diskquota for your account. To check your disk quota, type the following:
% quota <return>
Disk quotas for user sbh3284 (uid 4210):
Filesystem blocks quota limit grace files quota limit grace
/home 1084 4096 6144 84 0 0
The limit Command
The limit command shows the maximumcomputing resources that can be allocated to a process. To see this listing,type the following:
% limit <return>
cputime 3:00:00
filesize unlimited
datasize 81920 kbytes
stacksize 2048 kbytes
coredumpsize unlimited
memoryuse 1022184 kbytes
vmemoryuse 1048576 kbytes
descriptors 96
Shell and Environment Variables
The set Command
The echo Command
The printenv Command
The setenv Command
The .login and .cshrc Files
UNIX systems use two types ofvariables to define your working environment: shell variables and environmentvariables.
Shell variables are knownonly to the shell in which they were created. If you start a new shell (commandinterpreter), the shell variables created in the previous shell are nottransferred to the current shell.
Environment variables areglobal variables and are independent of the shell. Environment variables stay ineffect regardless of what shell is used.
On a UNIX system, some shelland environment variables are predefined by the system. Also, environmentvariables are usually represented by uppercase names whereas shell variables arerepresented by lowercase names. A shell variable with the same name as anenvironment variable still has the same function.
Some of the definable shellvariables are:
Variable
Description
argv
Argument to the shell.
autologout
Number of minutes of idletime before a user is logged out.
cdpath
Alternative directory treesearch.
history=n
Remember last n commands.
home
Home directory of user.
Directory where shellchecks for user's mail.
noclobber
Prevents overwriting anexisting file during redirection.
user
Login User ID.
savehist=n
Remember last n commands atthe beginning of next terminal session.
prompt=string
Change the default commandprompt to string.
path
Current path specification- list of directories the system may search to resolve command requests.
shell
Shell used to processcommands.
term
Terminal type.
status
Returned by last command:0=no error, 1=error.
Some of the definableenvironment variables are:
Variable
Description
HOME
Home directory.
SHELL
User's login shell.
TERM
Terminal type.
USER
Login User ID
PATH
Search path used to resolvecommand requests.
DISPLAY
Name of X Windows capabledisplay device.
The set Command
The set command displays currentshell variables and their values. You can also designate a new value for avariable with the set command. In the following example, current shell variables are shown using theset command:
% set <return>
argv ()
autologout 0
cdpath /home/dept/jsmith
cwd /home/dept/jsmith
history 20
home /home/dept/jsmith
mail /usr/spool/mail/jsmith
path (. /home/dept/jsmith/bin /home/dept/bin )
prompt %
shell /bin/csh
status 0
term vt52
user jsmith
%
In the following example, theshell variables term, prompt, and autologout are assigned values using theset command:
%set term=vt100 <return>
% set prompt="UNIX> " <return>
UNIX> set autologout=20 <return>
UNIX> set <return>
argv ()
autologout 20
cdpath /home/dept/jsmith
cwd /home/dept/jsmith
history 20
home /home/dept/jsmith
mail /usr/spool/mail/jsmith
path (. /home/dept/jsmith/bin /home/dept/bin )
prompt UNIX>
shell /bin/csh
status 0
term vt100
user jsmith
UNIX>
The echo Command
To display the value of ashell variable, type echo followed by a dollar sign ($) and the name of the variable. You must place a dollar sign before thevariable name to display the value of the variable otherwise the name of thevariable is displayed. In the following example, the echo command is used to displayboth text and the current values for the cwd and user variables:
% echo "Hello there" <return>
Hello there
% echo "cwd" <return>
cwd
% echo "$cwd" <return>
/home/dept/jsmith
% echo "$user" <return>
jsmith
%
In the following example, theecho command displaysthe values of the environment variables USER and TERM:
% echo "USER" <return>
USER
% echo "$USER" <return>
jsmith
% echo "$TERM" <return>
vt100
%
The printenv Command
The printenv command displays allenvironment variables and their values. In the following example, the printenv command displays theenvironment variables:
% printenv <return>
TERM=vt100
HOME=/home/dept/jsmith
SHELL=/bin/csh
USER=jsmith
PATH=.:/home/dept/jsmith/bin:/home/dept/bin
%
The setenv Command
The setenv command sets the valueof environment variables. In the following example, the environment variableTERM is set to vt102 with the setenv command:
% setenv TERM vt102 <return>
The .login and .cshrc Files
When you log in to a UNIXsystem using the C shell (the default shell), the system searches your homedirectory for two files, .cshrc and .login, and executes all of the shellcommands in those files. The commands in the .cshrc file are executed first,then commands in the .login file are executed. The two files differ in that thecommands in .cshrc are executed every time you start a new C shell, whereas thecommands in .login are executed only when you log in. If you start a new Cshell, the commands in .login are not re-executed. For users who invoke theBourne shell when they login, the system searches for a .profile file andexecutes all the shell commands in that file.
Usually, all of theenvironment variables are defined in .login and all of the shell variables aredefined in .cshrc. In the following example, the cat command displays thecontents of files .login and .cshrc:
% cat .login <return>
setenv SHELL /bin/csh
set mail=/usr/spool/mail/$user
% cat .cshrc <return>
set path=(. $HOME/bin /home/dept/bin /bin)
set history=20
alias dir 'ls -l'
alias rm 'rm -i'
alias cp 'cp -i'
alias mv 'mv -i'
set noclobber
set autologout=20
%
You can start a new C shellunder the parent shell by issuing the csh command. All of the commands defined in the .cshrc file areautomatically executed in this newly created C shell. Pressing <ctrl-d> kills the mostrecently created C shell.
Using X Windows Systems
Using X Windows With a Workstation
Starting X Windows on an NCD X Windows System
Accessing UNIX Documentation Using X Windows
To use X Windows you musthave a terminal or workstation that supports X Windows protocols. If you areuncertain whether your terminal or workstation can support the X Windowsprotocols, please consult your documentation or call Academic Computing Servicesat 272-2208.
The Teleray VT100 compatibleterminals in the computing facilities do not support X Windows protocols. Theterminals in the computing facilities that support X Windows protocols are theNCD HMXpro terminals.
If your terminal orworkstation does support X Windows protocols, then you can use X Windows withany host system that supports X Windows applications.
Using X Windows With a Workstation
To use X Windows with aworkstation, follow these steps:
1. Log in to thelocal workstation.
2. Start X Windowson the local workstation.
3. From the localworkstation, enter the command xhost +node (where node is the name of the remotenode where you will be running X Windows applications).
4. Connect and login to the remote node.
5. If the remotesystem is administered by Academic Computing Services, then enter the commandsetx on the remotesystem to set the DISPLAY environment variable.
or
If the remote system is not administered by Academic Computing Services, thenenter setenv DISPLAY <IPaddress>:0,where <IPaddress> is the IP address of your local system (you must type setenv in lowercase letters andDISPLAY in uppercaseletters).
You may then start any XWindows applications on the remote system and they will display on the localworkstation.
Starting X Windows on an NCD X Windows System
To start an X Windows sessionfrom an NCD X Windows System, follow these steps:
1. Select hostfrom the chooser window.
2. Connect and login to the remote node.
or (for a Telnet session):
1. Press the setupkey and select terminals, new terminal.
2. Connect and login to the remote node.
3. If the systemis not administered by Academic Computing Services at UT Arlington, then enter thefollowing:
% setenv DISPLAY <terminal>:0<return>
where <terminal> is the number of the terminal which can be found at the top of the monitor. Toenter this amount, you must be in the csh or tcsh shell and setenv must be in lowercaseletters and DISPLAY must be in upper case letters. For example:
% setenv DISPLAY xncd02:0 <return>
You may then start any XWindows applications on the remote system and they will display on your XTerminal.
If you subsequently useTelnet to connect with another system not administered by Academic ComputingServices at UT Arlington, you must perform step 3 listed above once again.
Accessing UNIX Documentation Using X Windows
To access UNIX documentationwhile using X Windows, type dxbook on the Omega system or answerbook on the Gamma system. These applications display online documentation on yourworkstation screen. When you start the application, you will see two types ofwindows.
The selection window displayslists of available online documentation. When you do not have a book open, theselection window contains lists of related documentation grouped intobookshelves. When you do have a book open, the selection window contains thetable of contents or index of that book.
The topic window lists thecontents of a book after that book is opened.
To open a book, follow thesesteps:
Open a book bydouble-clicking on that book's title once opened, you'll see the Table of Contents for that book in the selection window and that book's first page in thetopic window.For more information on usingthe dxbook or answerbook commands, includinga complete list of options, use the man command.
Available To:
- Event-Based
- Students Admitted to UT Arlington
- Departments and Offices at UT Arlington
- Retirees
- Vendors
- Visitors and Guests
- Faculty (currently appointed) and Staff
System requirements: Linux, None, Solaris

