UNIX for beginners

1.  Introduction: What is UNIX ?

UNIX is the name of a collection of software known as an operating system (OS) that runs on most computers.  The OS software is the means by which the user communicates with the computer's central processing unit (CPU) and memory by means of a keyboard and mouse (for input) and display monitor (for output), in order to perform computations.  The OS software is also responsible for communications between the CPU/memory and the computer's other peripherals such as disks, tapes, printers, dials, networks, etc., allowing these to be shared with other users (multi-user system), and/or with other jobs that a single user is running simultaneously (multi-tasking system).  The OS ensures that no two users or jobs can access the same device (CPU, memory, peripherals) at the same time; one is allowed to proceed while the other is forced to wait until the device is no longer busy.

The user should realise that the name UNIX does NOT refer to a single well-defined collection of software (even though the name was originally meant to imply "unique system"!), and that there is no such thing as "standard UNIX".  UNIX is rather a generic term for a number of superficially similar collections of software that differ in their detailed modes of operation, depending on the supplier of the OS software (usually but not always the same supplier of the CPU).  These apparently arbitrary variations are a major source of confusion and frustration particularly for novice users.

2.  Basic concepts.

2.1.  The UNIX nut: kernel and shell.

The main control program in a UNIX OS is called the kernel.  However the kernel does not allow the user to give it commands directly; instead when the user types commands on the keyboard they are read by another program in the OS called a shell which parses, checks, translates and massages them in various ways to be described later, then passes them to the kernel for execution.  (The analogy is with a nut - as in walnut - the important part of which is the kernel inside; the shell is merely the face that the nut presents to the outside world!)  Modern shells aim to reduce the amount the user has to type by providing facilities such as command recall and edit, command spelling correction, command or filename completion, and "wildcard" characters (characters in filenames that represent multiple possibilities).

There are a number of different shells available, with names such as sh, csh, tcsh, ksh, bash, each with different rules of syntax; these are partly though not completely responsible for the diversity of UNIX.  Once the command has been interpreted and executed, the kernel sends its reply, which may simply be a prompt for the next command to be entered, either directly to the display monitor, or more usually if a windowing system (e.g. X-windows) is in operation, via a display manager (e.g. xdm).  This is a program responsible for deciding where and in what form the output will appear on the display monitor.  If for any reason the kernel cannot perform the command requested (wrong syntax, for example), the reply will be an error message; the user must then re-enter the corrected command.

2.2.  Commands and processes.

The kernel and the shell programs running in the CPU are examples of processes; these are self-contained programs that may take over complete control of the CPU.  Although there can only be one kernel process running in a particular CPU, there may be any number of shell and other processes, subject of course to memory limitations.

Some commands to the shell are internal (or built-in), that is they only involve the shell and the kernel.  Others are external and may be supplied with the OS, or may be user-written.  An external command is the name of a file which contains either a single executable program or a script.  The latter is a text file, the first line of which contains the name of a file containing an executable program, usually but not necessarily a shell, followed by a sequence of commands for that program.  A script may also invoke other scripts - including itself!  Its purpose is simply to avoid having to re-type all the command it contains.

A command may also be an alias for an internal or external command (e.g. the user may not like the UNIX name "rm" for the command which deletes files, and may prefer to alias it to "delete").

The external command may optionally cause execution of the shell process to be temporarily suspended, and then run another program, which may then take over input from the keyboard and mouse and send output for display.  The shell may or may not wait for the program to finish, before it wakes up again and cause its prompt to be displayed.  It is very important that the user be continuously aware of which process is currently reading keyboard input: the shell or another program, because they usually speak completely different languages!

The above is an example of a parent process - the shell, and a child process - the external program.  In fact the child could just as well have been, and often is, another invocation of the same shell, or of a different shell, and the child process can be the parent of other child and so on (almost) ad infinitum.  Consequently a typical UNIX system has many processes either waiting or running.

2.3.  UNIX plumbing: pipes and inter-process communication.

Many UNIX commands by themselves perform very simple tasks; the power of UNIX derives from its capability to combine these in order to perform more complex tasks.  Commands may be run sequentially so that the output which results when each command acts on its input data becomes the input for the next command in the sequence - this is called a pipe.  Shell scripts may also make use of pipes and other control structures such as variables, condition tests and loops.  UNIX also has extensive facilities for inter-process communication (in addition to the pipe mechanism).

2.4.  Foreground, background and batch.

The user needs to be aware that there are 2 basic ways of running jobs (i.e. commands, programs and scripts) on a UNIX system: foreground and background.  There is also batch mode, but this is similar to background, with the exception that the jobs are held in a batch queue for sequential execution instead of all being run simultaneously.  In foreground mode the parent process is suspended while the child process runs, taking over the keyboard and monitor; when the child process terminates the parent process resumes from where it was suspended.

In background mode the parent process continues to run using the keyboard and monitor as before, while the child process runs asynchronously.  In this case it is advisable that the child process get all its input and send all its output to or from files and not to or from the keyboard and monitor, in order to avoid confusion with the parent process's input and output.  When the child process terminates, either normally or by user intervention, the event has no effect on the parent process, though the user is informed by a message sent to the display.  The user may also elect to place a child process already running in foreground into the background and resume the parent process, or to bring a background process into the foreground.  The user may actively terminate (kill) any process, provided he/she owns it (the user owns any process he/she initiates plus all descendants of that process), or downgrade (but not upgrade!) the priority of any owned process.

2.5.  UNIX file system.

Like other OS's UNIX organises information into files, and related files may be conveniently organised in directories.  Files may contain text, data, executable programs, scripts (which are actually just data for a scripting program such as a shell), and may also be links to other files, or to physical devices or communications channels.

The directory structure is hierarchical with the root directory, indicated by a forward slash (/), at the base of the tree.  This may contain files as well as other directories such as /bin, /etc, /lib, /tmp, /usr, and /d.  Actually in this example the root directory will contain directory files called bin, etc, lib, tmp, usr and d, each of which contains a list of files and their locations on the disk for each of the corresponding directories.  Each directory may contain further ordinary files and directory files, and so on.  The / character is used to delimit the components of the name.  For example the /d directory may contain directories such as /d/user1 and /d/user2 and these may contain the users' home directories such as /d/user1/tom, /d/user1/dick and /d/user2/harry, which are the directories that users tom, dick and harry respectively normally see when they first login to the system.

The entire directory hierarchy may reside on a single physical disk, or it may be spread across several disks; the boundaries between physical disks cannot be seen merely by looking at the directory hierarchy.  Your system administrator will decide where your home directory is to be both physically and logically located.

Every file in the hierarchy is identified by a pathname, this is merely a description of the the path you have to traverse to get from the root directory to the file.  E.g. the file junk.data (not a wise choice for a file containing data you wish to keep!) in directory /d/user1/tom/keep has the pathname /d/user1/tom/keep/junk.data .  This is an absolute pathname, because it starts with a / .  The pathname of a directory may be optionally terminated by a / ; e.g. in the example above /d/user1/ means the same as /d/user1 .  Strictly, a filename is distinct from a pathname; a filename is just one of the components of the pathname delimited by /'s.

Relative pathnames which have a start point anywhere but / in the hierarchy may be used instead, and are often more convenient.  Starting from /d/user1/tom/keep the relative pathname of the previous example is just junk.data or ./junk.data (because "." means the current directory).  Starting from user tom's home directory it would be keep/junk.data.  User dick in his home directory might refer to the same file either by its absolute pathname or by the name ../tom/keep/junk.data (".." means the parent directory which contains the current directory).  User harry residing in /d/user2/harry would have to use the absolute pathname or ../../user1/tom/keep/junk.data .

A useful shorthand for the home directory is ~ (though this syntax is not supported by all shells), so Tom can also refer to the same file by the absolute pathname ~/keep/junk.data, and Harry can use ~tom/keep/junk.data .

Another shorthand is the use of "wildcard" characters in filenames, technically called filename globbing.  The * character in a filename represents any string of characters, including no characters; the ? character represents any single character; a string of characters between [] represents any one of those specific characters.  These wildcard characters may be used more than once, and may appear in combination in a pathname.  Thus * by itself would be expanded to a complete list of filenames in the current directory, whereas ? would be expanded only to a list of 1 character filenames (if any), ?? to a list of 2 character filenames, and so on.  If there are files called "fee", "fie", "foe" and "fum" in the current directory, the strings f* and f?? would be expanded to the full list of names, whereas f?e and "f[eio]e" would be expanded to "fee fie foe" ("fum" doesn't match the last two patterns).  It is important to understand that it is the shell that is responsible for this wildcard expansion, and it does it completely mechanically without regard for any "intended" meaning (see example of the mv in Unix exercises section).

Last, but not least, note that UNIX is always fussy about the case of letters in commands, usernames, passwords and filenames; so Junk.data is not the same file as junk.data .

2.6.  The shell environment.

Each instance of the shell has its own environment of aliases, local variables and global (or environment) variables.  Aliases and local variables are local to the shell, and are not passed on to any other process, whether parent or child.  Global variables are inherited from the parent by the child, but not vice versa.  Local variables are conventionally given lower case names, while global variables have upper case names.  Global variables include the home directory (HOME), the path (PATH), the current directory (PWD), the shell (SHELL), and the terminal type (TERM).

The path is a list of directory filenames which is searched for external commands or scripts whenever the command or script name does not contain a directory specification; if there is more than one instance of the file in the path, the first one found is executed.  Note that the alias list is always searched first, followed by the list of built-in commands, followed by the directories in the path in sequence.  If the command contains a directory specification (e.g. ./run) none of the alias, built-in command or path lists are checked.

2.7.  Syntax of UNIX commands.

The general form of a UNIX command is:  command  [option(s)]  [argument(s)]  (the [] here indicate that the items they contain are optional; they are not part of the syntax).

If a typing error is made the line may be changed using the left/right arrow keys to move the cursor and the Backspace key to delete the character to the left of the cursor; new characters are inserted before the cursor.  When the line is correct use the Enter key to execute the command.  It is not necessary to move the cursor to the end of the line before pressing Enter.  The command may be cancelled before execution by using Ctrl-u (hold down the Ctrl key and press the u key).  If an incorrectly spelled command is entered and spelling correction is enabled in the shell, the shell will attempt to correct the mistake and ask for verification.

If the shell has filename completion enabled, use of the Tab key after part of a command or filename has been typed will cause the shell to attempt completion of the name, up to the character where the result is unique.  Use of the Ctrl-d key will cause all names that match what has been typed to be listed.

The options and arguments if present must be separated from the preceding item by a least 1 space.  However multiple options may or may not need to be separated from each other by at least 1 space; multiple arguments are always separated from each other by at least 1 space.  Options usually start with -, but occasionally it is a +, and sometimes the - or + may be omitted.

A line may contain several commands (each possibly followed by options and/or arguments) separated by semicolons (;).  The commands are executed in sequence, just as if they had been typed on separate lines.  If it is necessary to continue a command onto the next line, end the line with a backslash (\), press Enter and continue typing on the next line.

In a script anything after a # on a line is treated as a comment, i.e. it is ignored.

To background a command simply add an ampersand (&) on the end.

Commands may be piped using a vertical bar (|) to separate them.  As an alternative to piping the output may be redirected to write to a file using >filename or appended to the file using >>filename.  This only redirects the standard output stream; redirection of error messages (standard error stream) requires a different syntax which is shell-dependent.  The standard input stream may be redirected to read from a file using <filename.  Either or both standard input and output may be redirected.  In a script the standard input stream may be redirected to read from the script by using <<terminator, e.g.:
command  [option(s)]  [argument(s)]  <<EOD
Input data goes here.
The terminator above must match the one given on the command line exactly and must start in the first character position.  Any sequence of characters may be used in the terminator, except for special characters like &|<>'"\ .  If it is preceded by a backslash (\) this has a special meaning: variables beginning with $ in the input data are not treated as shell variables.

2.8.  Getting help.

Knowing how to get information from the computer is always a first priority!  The most common method is by means of the "manual pages", by typing  man command  where command is what you want information on.  Unfortunately this doesn't help if you don't know what you are looking for, and UNIX's command names are far from obvious!  You can try typing  man  -k  word .  This searches the headings of all the manual pages for word, and may produce both useless and useful information on what to try next!  Some systems have info installed; this is much better organised than man, though it may not be complete.  Type  info  followed by  h  if you're a first-time user, then follow the instructions.  Typing  help  on some systems gives you information on the built-in shell commands; alternatively try  man csh  (or whatever shell you're using).

3.  UNIX commands.

3.1.  Process and screen control.

Note that some of the Ctrl key functions may have been altered by an stty command; use stty -a to get the current settings.

Ctrl-cKill foreground process
Ctrl-zSuspend foreground process
Ctrl-dTerminate input, or exit shell
Ctrl-sSuspend output
Ctrl-qResume output
Ctrl-oDiscard output
Ctrl-lClear screen

3.2.  Line recall and editing (T shell).

Key or commandFunction
Up-arrowRecall previous command
Down-arrowRecall next command
!nRecall history line n
!textRecall last line beginning with text
Left-arrowMove cursor left
Right-arrowMove cursor right
Ctrl-aMove cursor to beginning of line
Ctrl-eMove cursor to end of line
Backspace or DeleteDelete character to left of cursor
Ctrl-dDelete character under cursor
Ctrl-uDelete whole line
Ctrl-kDelete line from cursor on
Ctrl-wDelete line to left of cursor
Ctrl-yPaste deleted text
Ctrl-tTranspose characters
Ctrl-rRefresh line

3.3.  Filename completion.

TabComplete filename up to next non-unique character
Ctrl-dList filenames matching partial name

Note that Ctrl-d has 4 possible functions, depending on the context.

3.4.  Input/output redirection and piping (C/T shell).

<Redirect standard input from file
<<Redirect standard input from command source
>Redirect standard output to file
>!Redirect standard output and overwrite file
>>Redirect standard output and append to file
>>!Redirect standard output to file or append to file
>&Redirect standard output/error to file
>>&Redirect standard output/error and append to file
>>&!Redirect standard output/error to file or append to file
|Pipe standard output to standard input
|&Pipe standard output/error to standard input
`command`Replace command with its output

3.5.  Table of equivalent commands for DOS users.

This table and the next should be used in conjunction with the DOS "help" and UNIX "man" commands on the particular operating system in use to check the definitive specification of the command options and arguments, as these often vary between different implementations of the OS.  Note that  {}  indicates a required variable argument;  []  indicates an optional one.

DOS commandUnix commandFunction
help  []man  []  {}Provide information about command
chkdsk  []df  []Show disk space
dir/w  []ls  []Wide directory listing
dir  []ll  []Long directory listing
dir/o:-d  []ll  -t  []Ditto in reverse creation order
dir/s  []ll  -R  []Recursive long listing
dir/p/s  []ll  -R  [] | moreDitto with pausing
cdpwdShow current directory
cd  {}cd  {}Change directory
cd  ..cd  ..Change to parent directory
cd  \cdChange to home directory
md  {}mkdir  {}Create empty directory
rd  {}rmdir  {}Delete empty directory
type  {}cat  []  []List file(s)
type  {} | moremore  {}  []Ditto with pausing
tv  {}less  {}  []Ditto
copy  {}  {}cp  {}  {}Copy file
rename  {}  {}mv  {}  {}Rename file
move  {}  {}mv  {}  {}Move file
sort  {}sort  {}Sort file
edit  {}emacs  {}&Edit file
del  {}rm  {}  []Delete file(s)
del/p  {}rm  -i  {}  []Ditto with confirmation
deltree  {}rm  -r  {}Recursive delete directory
pkzip  {}gzip  {}Compress file(s)
pkunzip  {}gunzip  {}Decompress file(s)
msbackup  []tar  cv  .Make backup
msbackup  []tar  xvRestore from backup
attrib  {}  {}chmod  {}  {}Change file attribute(s)
fc  {}  {}diff  {}  {}List file differences
find  "{}"  {}grep  {}  {}Search file(s) for character(s)
print  {}lpr  -P{}  []Print file
printlpq  -P{}List printer queue
print/clprm  -P{}  {}Delete print job
doskey/hhistoryShow command history
doskey  {}={}alias  {}  {}Create command alias
setsetShow local variables
set  {}={}set  {}={}Set local variable
pathecho  $PATHShow executable path
path  {}setenv  PATH  {}Set executable path
for  {}  {}foreach  {}  {}Loop command
commandtcsh  []Start child shell
{}  []{}  []Run program or script
rem  []#  []Use comment in script
echo  {}echo  {}Display message in script
if  {}  {}if  {}  {}Conditional command
goto  {}goto  {}Jump to label in script
clsCtrl-lClear screen
Ctrl-cCtrl-cKill foreground process
Ctrl-zCtrl-dSignal end of input
PauseCtrl-sSuspend output to screen
SpaceCtrl-qResume output to screen
exitexit  []Exit from script or shell

3.6.  Additional useful UNIX commands by category.

3.6.1.  File manipulation.

Unix commandFunction
du  []Show disk usage
ln  {}  {}Create directory entry (hard link)
ln  -s  {}  {}Create soft link to file
file  {}Show type of file
which  {}Locate executable file in path
touch  {}Create empty file or change file access time
tee  {}Copy standard input to file and standard output
wc  {}Show file length
head  []List top lines of file
tail  []List bottom lines of file
fgrep  {}  []Search file(s) for fixed string
egrep  {}  []Search file(s) for extended regular expression
find  {}  []Multiple file commands
cut  []Extract columns from file
sed  {}  []Edit file in stream mode
awk  {}  []Process column data
fold  []Fold long lines in file
paste  []Merge lines of files
zcat  []List compressed file
dd  {}  {}Convert file format
od  {}Dump file
nl  []Number lines in file
source  {}Read commands from file

3.6.2.  Process control.

Unix commandFunction
yppasswdChange password
sttyShow or set terminal characteristics
bindkeyShow or set key bindings
allocShow memory allocation
limitShow process limits
limit  {}  {}Change process limit
umask  {}Change permission for new files
xargs  {}  []Execute command with passed arguments
tr  {}  {}Translate character(s)
setenvShow global variables
setenv  {}  {}Set global variable
unset  {}Unset local variable
unsetenv  {}Unset global variable
echo  ${}Show value of variable
nice  {}  []Run command at low priority
renice  {}  {}Reduce priority of command
Ctrl-zSuspend foreground process
jobsList background jobs
ps  []Show process status
bg  []Put job in background
fg  []Put job in foreground
stop  {}Suspend background process or job
kill  {}Signal or kill process or job
batch  []  []Submit command script to batch queue
wList logged-in users
sleep  []Wait for time interval
time  []Time a command
while  {}Conditionally execute loop
logoutTerminate current session

3.6.3.  Networking.

Unix commandFunction
finger  []List user information
talk  []Exchange messages with other user
pineUse e-mail
ftp  []Transfer file(s) via network
telnet  []Remote login via network
rlogin  []Ditto
rsh  {}  []Remote shell command via network
rcp  {}  {}Copy file(s) via network

3.6.4.  Programming.

Unix commandFunction
ci  {}Check file into revision control
co  {}Check file out of revision control
make  []Update program
f77  {}Compile Fortran 77 program
fsplit  {}Split Fortran source into subroutines
cc  {}Compile C program
c++  {}Compile C++ program
perl  {}Compile and run Perl program

3.6.5.  Miscellaneous.

Unix commandFunction
dateShow today's date
calShow calendar
bcEvaluate arithmetic expression(s)

4.  Emacs survival guide.

Emacs has a vast range of commands, here is just a brief personal selection of the ones I use most.

Emacs commandFunction
Ctrl-hGet online help (e.g. Ctrl-h t for tutorial)
Ctrl-x Ctrl-fOpen file in new buffer
Ctrl-x Ctrl-sSave active buffer to existing file
Ctrl-x Ctrl-wSave active buffer to specified file
Ctrl-x sPrompt to save changed buffers to their files
Ctrl-x iInsert another file
Ctrl-x Ctrl-bList all buffers
Ctrl-x bSelect specified buffer
Ctrl-x kKill specified buffer

Note that the above file and buffer manipulation commands are not needed for versions of Emacs that run in an X-window and have a File/Buffers menu bar.  In the following "motion" commands note that the Alt Gr key sometimes works as Alt.

Emacs commandFunction
Up/down arrowMove up/down 1 line
Left/right arrowMove left/right 1 character column
Alt-fMove forwards one word
Alt-bMove backwards one word
Ctrl-eGo to end of line
Ctrl-aGo to beginning of line
Alt->Go to end of file
Alt-<Go to beginning of file
Ctrl-vGo down one screenful
Alt-vGo up one screenful
Ctrl-lCentre current line
Alt-x goto-line
Go to line number n
Ctrl-sIncremental search forwards
Ctrl-rIncremental search backwards
Alt-%Global replace with prompt
Ctrl-gCancel current operation
DeleteDelete character before cursor
Ctrl-dDelete character under cursor
Ctrl-kKill to end of line or delete blank line
Ctrl-yPaste in (yank) last block of text killed or selected
Alt-yPaste in any previous block of text killed or selected
Ctrl-_Undo last change (may be repeated)
Ctrl-SpaceSet mark
Alt-wSelect region between mark & cursor
Ctrl-wKill region (cut) between mark & cursor

Note that the above cut and paste commands are not needed for versions of Emacs that run in an X-window and have an Edit menu.  Also the mouse can be used to select text by dragging with the left button down, moving the mouse cursor to the insertion point and using the middle button to paste.

Emacs commandFunction
Ctrl-c Ctrl-rColumn numbers (Fortran mode only - starts at 0!)
Ctrl-c Ctrl-wMake window 72 columns wide for Fortran
Ctrl-x 2Split window vertically
Ctrl-x 3Split window horizontally
Ctrl-x oSelect another window
Ctrl-x ^Make window taller
Ctrl-x }Make window wider
Ctrl-x 1Kill all but active window
Ctrl-x 0Kill active window
Alt-x shellStart shell in Emacs window
Ctrl-x Ctrl-cExit Emacs

Some of the above functions are not implemented in some versions of Emacs.

5.  Some basic vi commands.

Vi commandFunction
:set nuShow line numbers
:set icIgnore case differences when searching
:set aiSet automatic indent
:set smShow matching ( or { with ) or } in insert mode
Up/down arrowMove up/down 1 line
Left/right arrowMove left/right 1 character column
0  $Go to 1st/last column of current line
EnterGo down to 1st printable character of next line
nnbMove right/left n words (1 word if n omitted)
nGGo to line n (end of file if n omitted)
Ctrl-Ctrl-bPage forward/backward 1 screen
Ctrl-Ctrl-uPage forward/backward half a screen
[[  ]]Go to beginning of current/next C function
/expressionEnterSearch forwards for expression
?expressionEnterSearch backwards for expression
n  NRepeat last / or ? command in same/reverse direction
ytargetCopy (yank) text up to target to buffer
YCopy current line to buffer
itextEscInsert text before cursor
otextEscOpen new line below cursor and insert text
rReplace character under cursor with next typed
RtextEscReplace text
BackspaceIn insert mode, delete character before cursor
x  XDelete character under/before cursor
nxDelete n characters under and to right of cursor
nXDelete n characters before cursor
ddDelete current line
nddDelete n lines
DDelete from cursor to end of line
p  PPut back yanked or deleted text below/above current line
JJoin current and next lines
:m,n s/old/new/gcGlobal replace (g=every occurrence on line, c=prompt)
m=. means from current position, n=$ means to EOF
uUndo last change
:qQuit, provided no changes were made
:q!Quit without saving
:wSave (write) changes
:m,n w fileSave lines m through n (default=all) to file
:xSave changes and quit

6.  Unix exercises.

#  <-- Note this means a comment - you don't have to type the comments!

# Set variable P to the PDB data directory.
setenv  P  /public/pdb/data  # Do this once for each instance of the shell.

6.1.  emacs exercise.

# First copy a file: note the "." at the end!
cp  $P/pdb6lyz.pdb  .
# ... and the character after "6" is an ell not a one.
# Set mode to write:
chmod  +w  pdb6lyz.pdb  # Don't forget to use filename completion.
# Define display for X application (once per shell):
setenv  DISPLAY  lundynn:0
# Edit the file in background; note the ampersand (&):
emacs  pdb6lyz.pdb&
# You'll find it easier if you make your shell and Emacs windows wider.

6.2.  sed & awk examples.

cp  $P/pdb6lyz.pdb  .                     # Make a fresh copy.
sed  s/GLU/GLN/  pdb6lyz.pdb              # Example of stream editing.
sed  s/GLU/GLN/  pdb6lyz.pdb >!  new.pdb
diff  pdb6lyz.pdb  new.pdb                # Check that new file is different.

awk  '($1=="ATOM") {print $6,$7,$8}'  pdb6lyz.pdb
awk  '($1=="ATOM") {print $4}'  pdb6lyz.pdb
awk  '($1=="ATOM") {if ($5!=s) {print $4; s=$5}}'  pdb6lyz.pdb >!  6lyz.seq
cat  6lyz.seq

6.3.  alias examples.

alias                              # See what aliases you have.
alias  h  history                  # Aliases save typing !
ls  -l
alias  ll  ls  -l                  # You may have this already.
alias  lh  'ls  -Alt  \!* | head'
lh                                 # Lists 10 most recent files.
lh  *.pdb

alias  run  '(time  tcsh  \!^:r.csh) >&\!  \!^:r.log&'
# Now make a script with emacs, e.g. "job.csh" and type "run job".

6.4.  cat & mv examples.

cat  >!  file1.c
This is file1.c
Ctrl-d  # This means hold down the "Ctrl" or "Control" key and
        # then press the "d" key.
cat  >!  file2.c
This is file2.c

# In VMS & DOS the following is OK: ren  *.c  *.cpp

alias  mv     # mv may be aliased to "mv  -i".
unalias  mv   # Remove "-i" safety check.

cat  file1.c
cat  file2.c
mv  file?.c  file?.C  # Note Unix distinguishes lower and upper case!
cat  file1.C  # What happened to your .c files?  Explain why!
cat  file2.C

6.5.  foreach example.

# First, re-create file1.c and file2.c as before.

rm  file?.C            # Delete the old output files.
foreach  x  (file?.c)
mv  $x  $x:r.C
end                # Should be OK now!

6.6.  Piping and backquoting examples.

setenv  Q  /public/pdb/current/ps  # Saves typing!
grep  -h  PROTEINASE $Q/*
ll  $Q | head  -6      # First 5 files in alphanumeric order.
ll  -t  $Q | head  -6  # First 5 files in time-reversed order.
ll  -t  $Q | tail  -5  # Last 5 files in time-reversed order.
grep  -h  PROTEINASE  `ls  $Q/* | head  -5`      # Note ` not ' !
grep  -h  PROTEINASE  `ls  -t  $Q/* | head  -5`
grep  -h  PROTEINASE  `ls  -t  $Q/* | tail  -5`
# What's the purpose of the "-h" flag on the grep command,
# and why is it necessary to specify "$Q/*" ?

6.7.  grep & find examples.

ls  $P    # Works.
ls  $P/*  # Fails!

grep  ASPARTIC  $P/*.pdb        # Fails!
set echo
grep  ASPARTIC  $P/pdb1pp?.pdb  # Now you see expanded command.
unset echo

find  $P  -name  \*.pdb  -exec  grep  ASPARTIC  {}  \;
# This is too slow!  So just select a few files:
find  $P  -name  pdb1pp\?.pdb  -exec  grep  ASPARTIC  {}  \;

# No filenames are printed:
# Insert  -print  before  -exec  above (use line recall!).
# Now you get all filenames!

find  $P  -name  pdb1pp\?.pdb  -print | xargs  grep  ASPARTIC
# The right way to do it!

6.8.  diff examples.

# Create file1 containing:  ab
# Create file2 containing:  a b
# Create file3 containing:  a  b

diff       file1  file2
diff  -ws  file1  file2
diff  -bs  file1  file2
diff       file2  file3
diff  -bs  file2  file3

6.9.  bg/fg examples.

stty  -tostop  # Allows output from background job.
set  notify    # Allows notification of background job status.
sleep  120; echo  wakey wakey&
# etc.

© IJT 06-Oct-1999