Академический Документы
Профессиональный Документы
Культура Документы
Multiuser with efficient multitasking Effective use of resources Security Available on many systems from PCs to Supercomputers
Flavors of UNIX
All the basic commands are the same. Differ mainly at the programmer's level. Major versions are the Berkeley Standard Distribution (BSD) and AT&T System V. Some Workstation Variants: SunOS & Solaris(SUN), AIX(IBM), IRIX(SGI), ULTRIX(DEC), HP- UX(HP) Some PC & Mac Variants: BSD/OS, Linux, SCO, ESIX, XENIX, AUX
Case Sensitivity
UNIX is case sensitive. Most commands and usernames are in lower case.
command: cd and CD are different username: smith, SMITH and Smith are all different
Getting On
UNIX is a multiuser operating system. To get on you need:
User ID: used to establish file ownership, mailbox, and is known to all users of the system. Password: used to verify the user ID. Keep your password secret!
Being at the console of a UNIX workstation Connecting to a remote UNIX workstation o Dial o Telnet
The system provides a message ending in "login:". Type your User ID at this prompt. "Password:" is the next prompt. Type your password. It will not echo.
In both cases, you must type correctly. Backspace will not function, and case matters. ^u will erase all of what you typed so you can try again.
Getting Off
Close the session when you are finished so that no one can modify your files or send mail from your account by entering exit Note: if you have running jobs you may have to enter exit a second time.
The man command displays information from the UNIX manual set. Use the command man man to see the options available on your system.
Navigating through the man command output: space move down a page ENTER move down a line b move back a page q quit man command usage: man [options] subject
gives information about the passwd command. Click here to give this a try. The manual pages have a facility similar to a book index which can be used to find the name of a UNIX command or all references to a particular subject.
Syntax:
man -k subject
date print the date and time finger lookup user information w lists information about logged in users who lists information about logged in users ps lists information about processes
The following are some useful UNIX commands related to files. Click on the highlighted commands to pull up the associated man page.
cd changes the current directory ls list the contents of a directory mkdir create a directory rmdir remove a directory cat concatenates of displays files cp copies files mv moves files rm removes files more look at a file one screen at a time tail look at the end of a file
Example:
ls -l *.dat
Use the man command to find detailed information about UNIX commands
UNIX Applications
Electronic Mail Text Editing Information Retrieval USENET News groups telnet/ftp
Basic e-mail services are built into UNIX The mail command can be used to send/read e-mail. (See the manual pages for mail for more information.)
Note: The mail user interface is rather primitive and not user friendly. Electronic Mail: Pine
We recommend using pine (Program for Internet News and Email) Full featured, including the pico text editor and a built-in newsreader. User friendly (and user configurable) interface Built-in on-line help facility
Note: pine is not built into UNIX, but is available for free.
Electronic Mail: Pine Main menu This is the Main menu for pine.
PINE 3.91 MAIN MENU Folder: INBOX 313 Messages
? C I L A S Q
HELP
Get help using Pine Compose and send/post a message View messages in current folder Select folder OR news group to view Update address book Configure or update Pine Exit the Pine program
Copyright 1989-1994. PINE is a trademark of the Univ. of Washington. ? Help P PrevCmd R RelNotes K KBLock
Typing ? will get you an introduction to pine. To perform another task, simply type the single letter associated with the task. For
example, to compose and send a message to another person, type c. Note that case is not important for commands issued within pine.
Message Composition in pine If you choose C from the main pine menu, you enter the message composition part of pine. Below is sample output of a composition session:
PINE 3.91 COMPOSE MESSAGE Folder: INBOX 313 Messages
To : wsg@listserv.uga.edu Cc : Attchmnt: Subject : What a great UNIX course ----- Message Text ----Isn't this a great Getting Started with UNIX course?!?! ^G Get Help ^X Send ^R Read File ^Y Prev Pg ^K Cut Text ^O Postpone ^C Cancel ^J Justify ^_ Alt Edit ^V Next Pg ^U UnCut Text^T To Spell
On-line help in the pine Composer From within the message composition part of pine, typing ^g will get you to the on-line help for the pine composer. Below is what the on-line help looks like.
PINE 3.91 Help on the Pine Composer COMPOSER COMMANDS CURSOR MOTION KEYS ^B (Left Arrow) |EDITING KEYS | ^D Delete current character Line 19 of 145 13%
Back character
^F (Right Arrow) Forward character | ^H (DEL) Delete previous character ^P (Up Arrow) Previous line | ^^ Set a mark ^N (Down Arrow) Next line | ^K Cut marked text or ^A Beginning of line | delete current line ^E End of line | ^U Paste text, undelete lines ^Y Previous page | cut with ^K, or unjustify ^V Next page |------------------------------------^@ (Ctrl-SPACE) Next word |SCREEN/COMPOSITION COMMANDS ---------------------------------------| ^W Whereis (search for string) MESSAGE COMMANDS | GENERAL COMMANDS | ^T Spell checker ^C Cancel | ^G Get help | ^J Justify paragraph ^O Postpone | ^Z Suspend | ^L Redraw Screen ^X Send | ^_ Alt. editor | ^R Read in a file E Exit Help - PrevPage Spc NextPage Y prYnt W WhereIs
The built-in full-screen editor in UNIX is vi Other common editors on UNIX systems
emacs jove xedit
pico command summary ^G ^F ^B ^P ^N ^A ^E ^V ^Y ^W ^L ^D ^^ ^K ^U ^I ^J ^T ^C ^R ^O ^X Display the on-line help. move Forward a character. move Backward a character. move to the Previous line. move to the Next line. move to the beginning of the current line. move to the End of the current line. move forward a page of text. move backward a page of text. Search for (where is) text, neglecting case. Refresh the display. Delete the character at the cursor position. Mark cursor position as beginning of selected text. Cut selected text (displayed in inverse characters). Uncut (paste) last cut text inserting it at the current cursor position. Insert a tab at the current cursor position. Format (justify) the current paragraph. To invoke the spelling checker Report current cursor position Insert an external file at the current cursor position. Output the current buffer to a file, saving it. Exit pico, saving buffer.
Text-based utilities USENET news telnet/ftp X-Windows-based utilities (discussed later) EFF's Guide to the Internet is available at the UCNS helpdesk. (Highly recommended)
USENET News: Getting Started People new to USENET should check the contents of the news.announce.newusers newsgroup. Articles explaining USENET, including network etiquette (netiquette) and Frequently Asked Question (FAQ) lists are available. Below is a recent listing of the articles on news.announce.newusers.
news.announce.newusers a b d e f g i j l o r s t u v w x y David C Lawrence the m team Brad Templeton Mark Moraes Mark Moraes Mark Moraes Mark Moraes Mark Moraes Mark Moraes Dave Taylor Mark Moraes Mark Moraes Edward Vielmetti Mark Moraes Perry Rovers Aliza R. Panitz Chris Lewis Russ Hersch 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 18 articles (moderated) How to Create a New Usenet Newsgroup Introduction to the *.answers newsgroups DRAFT FAQ: 10 big myths about copyright explained Emily Postnews Answers Your Questions on Netiquette A Primer on How to Work With the Usene Community Introduction to news.announce How to Get Information about Networks Answers to Frequently Asked Questions about Usenet Rules for posting to Usenet A Guide to Social Newsgroups and Mailing Lists Usenet Software: History and Sources Hints on writing style for Usenet What is Usenet? A second opinion. What is Usenet? Anonymous FTP: Frequently Asked Questions (FAQ) List How to find the right place to post (FAQ) How to become a Usenet site FAQs about FAQs
Sample rn session
% rn (Revising soft Unread news in Unread news in Unread news in pointers -- be patient.) uga.general uga.tech uga.announce.ucns
Finding new newsgroups: Newsgroup Newsgroup Newsgroup Newsgroup Newsgroup Newsgroup alt.support.telecommute not in .newsrc -- subscribe? [ynYN] alt.fan.barney not in .newsrc -- subscribe? [ynYN] alt.philboyd.studge.is.a.dork not in .newsrc -- subscribe? [ynYN] rec.crafts.needlepoint not in .newsrc -- subscribe? [ynYN] soc.culture.swaziland not in .newsrc -- subscribe? [ynYN] alt.travel.canada.ontario.toronto not in .newsrc -- subscribe? [ynYN]
Used to connect to remote computers You need an account on the remote machine
tn3270
Used to transfer files from a remote computer Anonymous ftp is available at many sites
Flavors of Unix
All the basic commands are the same. Differ mainly at the programmer's level. Major versions are the Berkeley Standard Distribution (BSD) and AT&T System V. Some Workstation Variants: SunOS & Solaris(SUN), AIX(IBM), IRIX(SGI), ULTRIX(DEC), HP-UX(HP) Some PC & Mac Variants: BSDI, LINUX, SCO, ESIX, XENIX, AUX
A shell is a program that reads commands and executes them. The common shells are the C shell (csh), the Bourne shell (sh), and the Korn shell (ksh). The shells differ in scripting syntax and a few other minor ways. You may be able to change your login shell using the chsh command.
If the following files exist in your home directory, they will be executed whenever you login: o csh: .cshrc and .login o sh and ksh: .profile Place commands or tasks into these files that you would like performed whenever you login.
sh:
dir() /bin/ls -l $*
ksh:
alias -x dir='ls -l'
Shell Variables
Shell variables are simply strings of characters that hold other values, for example, $HOME may stand for /home/jones. Shell variables are indicated to the shell by a "$" as the first character.
To see all of your built-in shell variables, use the set command.
Shell Variables
In general, shell variables that are special to the shell are written in uppercase, and user-assigned shell variables are written in lowercase: Examples:
$HOME $myvar
To see the value of a specific shell variable, use the echo command:
echo $HOME
Shell Variables
Several environmental variables are special to the shell. These include:
$HOME your login directory $PATH directories that will be searched for commands $TERM your terminal type $DISPLAY your local hostname for X windows applications
Shell Variables
To set shell environmental variables:
csh:
setenv PATH /usr/bin:/bin setenv PATH $PATH\:$HOME/bin
sh, ksh:
PATH=/usr/bin:/bin export PATH PATH=$PATH\:/usr/bin:/bin export PATH
Shell variables in commands are expanded by the shell. Shell variables are indicated by a "$" as the first character (e.g. $PATH, $HOME). Examples:
echo $PATH cd $HOME ls $dir1
Send standard output from the first command to the standard input of the next Examples:
ls > dir.list ls $dir1 | more
The top of the tree, commonly called the root, is denoted by a single forward slash (/). All files are located "below" the root directory.
Relative paths (no slash at the beginning) start their search in the current directory:
more adir/kermit.txt
Show the current directory with the pwd command. The cd command (change directory) is used to move around the directory tree. Examples for the tree given above are:
cd / cd /usr/jones cd
There are two special relative path symbols, '.' and '..' . These indicate the current directory (.) and its parent (..). Examples:
ls ../smith cd ..
mkdir:
Create new directories with the mkdir command. It makes the named directory.
Some UNIX systems allow creation of many levels of directory at once. Examples:
mkdir project mkdir project/data
rmdir:
Remove a Directory
Delete a directory with the rmdir command. The directory to be deleted must be empty of both files and other directories. Directories must be deleted from the bottom up. Examples:
rmdir project/data rmdir project
mv:
Move a File
The destination file is replaced if it exists. The original file is removed, so use with caution.
cp:
Copy a File
The cp command copies a file from one name or place to another. Examples:
cp a.dat a.old cp a.dat ../save (directory) cp a.dat ../save/a.old
rm:
Remove/Delete a File
The rm command is used to remove or delete one or more files. The -i option will ask you about each file to be removed. There is no way to recover a file after it has been removed. Examples:
rm x.y rm a.dat b.dat c.dat d.dat rm -i *.o
ls:
The ls command lists the files in directories. Some of the more common options are:
-F -l -a -t
type of file with "/", "*", "=", "@" files in a long, descriptive format all entries, including "dot" files files in reverse order of time created
Examples:
ls ls -Fla ls -Fla *.c ls -Fla adir (directory)
find:
The find command locates specified files and lets you perform a number of actions on (or to) them. find will search recursively down the directory tree starting at the directory specified on the command line. find uses words for options, not single letters. Some of the more common options are:
-name fn look for the filename specified -print print the filenames found -exec cmd run the command "cmd" -newer fn find files newer than the file "fn"
Examples:
find . -name slides.txt -print find / -name \*.c -print find / -name \*.old -exec rm -i {} \;
file:
Use this before using either cat or more to look at a file at a terminal. Types are: text, binary executable, commands, data, etc. Never bring binary executable files to a terminal and be careful with data. Examples:
file x file * | more
more:
The more command is used to look at the contents of a file, one screenful at a time. more also allows you to break up output to standard output to one screen at a time. To continue, press the spacebar; to quit, "q" For help, press "h" while more-ing a file. Examples:
more letter.doc more *.doc ls /usr/lib | more
tail:
The tail command displays the end of a file. Specify the number of lines displayed by including a number preceded by a "-". The tail of a file being created by another process may be viewed continuously (this flag varies from system to system; check the tail man page). Examples:
tail letter.doc tail -100 letter.doc | more
Compare Files
Output lines are flagged with "<" for the first file and ">" for the second file. Example:
diff file1 file2 1c1 < this is file1 --> this is file2
Unix is a multiuser, multitasking operating system (task = process). On a Unix system, it is possible to run many programs and commands (processes) at the same time. Each user can have multiple processes running at the same time. The ps command is used to look at processes running on the system. The arguments to and output from this command depends on the flavor of Unix that you are running. ps by itself will show all running processes that are associated with your current terminal. Example of output from ps
PID TTY TIME CMD 16035 pts/1 0:00 ps 19628 pts/1 0:00 ksh
System V systems (AIX, IRIX, Solaris, Linux): o ps -ef all processes, full listing o ps -fu user all processes associated with user, full listing
BSD systems (SunOS, AIX, BSD/OS): o ps aux all processes, full listing o ps u all processes associated with running user, full listing
Note that the output is redirected to a file - otherwise, it would be sent to standard output and may interfere with what else you are doing.
If the program expects input from the keyboard, this input must be redirected from a file or else the program will fail.
Typical session:
runme > cmd.out & [1] 19518 jobs [1] + Running runme > cmd.out &
The number in square brackets is the jobid and is identified by a leading "%"
Example:
kill 12345 kill %jobid kill the background job
Example:
kill %1
Example:
See the manual page for your shell (csh, ksh etc.) for additional job control commands
There are a number of commands built into Unix to provide the ability to archive and compress files. A number of public domain programs are also available.
The tar command is used to write data to tape and create multi-file archives on disk. Examples: Create file containing all files in a directory:
tar cvf files.tar adir
Use the compress command to shrink files. The compress command will add a ".Z" to the end of the compressed file:
compress letter.doc
Often, tar and compress are used together to create file archives for storage or distribution. These files will have a name of the form "something.tar.Z" To look at the contents of a ".tar.Z" file:
zcat files.tar.Z | tar tvf - | more
To zip files:
gzip file.txt
To unzip files:
gunzip file.txt.gz
gunzip -c file.txt.gz
Other commands may be available, including: o zip and unzip - compatible with DOS zip. File suffix is ".zip". This is a public domain program and not included with the standard Unix operating system. o pack and unpack - usually included with Unix. These files have the suffix ".z"
A shell is a program that reads commands and executes them. The common shells are the C shell (csh), the Bourne shell (sh) and the Korn shell (ksh). The shells differ in scripting syntax and a few other minor ways. You may be able to change your login shell using the chsh command.
Shell variables are simply strings of characters that hold other values, for example $HOME may stand for /home/jones. Shell variables are indicated to the shell by a $ as the first character. To see all of your built-in shell variables, use the set or env commands. In general, shell variables that are special to the shell are written in uppercase, and user-assigned shell variables are written in lowercase: Example:
$HOME $myvar
To see the value of a specific shell variable, use the echo command:
% echo $HOME
To access the value stored in a shell variable, specify the variable including the "$". Example:
% setenv prog /usr/local/apps/fft
Matches a list or range of characters at one position. Some valid ranges are [a-z], [A-Z], and [0-9].
{..}
Substitution list -- left to right order is preserved. Matches are sorted at a low level to preserve this order.
~
Commands can be substituted in a similar manner to shell variables. Enclose a command in back-tics, (` `) to substitute it into another expression. Example:
% setenv users `who | wc | awk '{print $1}'` % echo On `date` there were $users users on. On Mon May 6 11:37:16 EDT 1996 there were 27 users on.
It is possible to redirect command input and output away from the keyboard and screen and from/to files:
<
Send standard output from the first command to the standard input of the next
Examples:
% ls > dir.list % ls $dir1 | more
The general form is a tree. The top of the tree, commonly called the root, is denoted by a single forward slash (/). All files are located "below" the root directory. Filenames are specified in one of three forms: Absolute paths begin with a slash:
% more /home/jones/adir/kermit.txt
Relative paths (no slash at the beginning) start their search in the current directory:
% more adir/kermit.txt
UNIX is a multiuser, multitasking operating system (task = process). On a UNIX system, it is possible to run many programs and commands (processes) at the same time. Each user can have multiple processes running at the same time.
ps:
The options to the ps command depend on the flavor of UNIX: System V systems (AIX, IRIX, Solaris, Linux, DEC Unix):
% ps -ef
at:
User can specify date and time to run a command or several commands in a file:
% at 15:00 command_file
% at now + 2 days command_file % at 3pm June 8 command_file % echo 'halt -q' | at now + 1 minute
The cron susbystem is used to run recurring commands (daily backups, accounting, etc.) The list of commands to run is found in the user's crontab file, usually located in the file:
/var/spool/cron/crontabs/userid Use the command crontab -e to create or modify the crontab file. crontab -l lists the contents of the crontab file.
crontab
File format
Comments begin with a # in the first column There are six fields in a crontab entry:
Minute: Hour: Day of Month: Month: Day of Week: 0-6 0-59 0-23 1-31 1-12 (0 = Sunday)
Command to run
Example:
# run backups at 9:00pm Monday through Friday 0 21 * * 1-5 /backup_files 2> /dev/null # run a program every 10 minutes 0,10,20,30,40,50 * * * * /home/jsmith/bin/send_data # run a program at 7:21am on the 1st day of every month 21 7 1 * * /home/jsmith/bin/monthly_program
nice:
CPU time on a UNIX computer is given to processes based on their priority. The nice command is used to run a command at a lower priority:
% nice mycommand & % nice -15 mycommand &
nohup:
In some shells, all background processes are terminated when you logout. To protect a process from hangups, run it with the nohup command: Example:
% nohup cc -c *.c &
By default, both standard output and standard error are redirected to the file nohup.out.
run a command when the system load permits. The syntax is similar to that of the at command.
Batch Queues
There are other queuing systems which may be installed on your system. Common batch systems are: LoadLeveler, NQS and DQS. Contact your local system adminstrator for information on queues as well as CPU limits for non-batch processes.
Advanced Commands
UNIX command philosophy Most commands perform only simple tasks. This leads to small and efficient commands. Several commands are used together to perform more complex tasks. The following commands, used alone or with other commands, are very useful.
awk:
awk matches patterns in files and performs operations on them. awk is also a programming language with a syntax similar to C.
It is commonly used as a filter for many problems. The awk utility is covered in detail in the UNIX Utilities II: awk training course. Examples Delete the second field of every line in the file a.dat
% awk '{$2= ""; print}' a.dat > a.dat.new Print the second field of every line in the file a.dat % awk '{print $2}' a.dat | more Print out all lines in the file a.dat that are longer than 72 characters: % awk 'length > 72' a.dat Kill all processes belonging to user jdoe % ps aux | awk '$1=="jdoe" {print "kill " $2}' | sh
awk
programs
Programs written in awk can be quite complex. Many numerical and string functions are available, as are variables and multi-dimensional arrays. To execute the awk program, program.awk:
% awk -f program.awk input_file
x1 += $1 x2 += $1*$1 } END { x1 = x1/NR x2 = x2/NR sigma = sqrt(x2 - x1*x1) if (NR > 1) std_err = sigma/sqrt(NR - 1) print "Number of points = " NR print "Mean = " x1 print "Standard Deviation = " sigma print "Standard Error = " std_err }
cut:
The cut command is used to write out selected characters or fields from each line of a file. Examples:
Compare files
Output lines are flagged with < for the first file and > for the second file. The output of diff is the list of ed commands needed to change the second file to the first. Example:
% diff file1 file2 1c1 < this is file1 --> this is file2
find:
The find command locates specified files and lets you perform a number of actions on (or to) them. find will search recursively down the directory tree starting at the directory specified on the command line. find uses words for options, not single letters. Some of the more common options are:
-name filename
Examples:
% find . -name slides.txt -print % find / -name \*.c -print % find / -name \*.old -exec rm -i {} \;
grep:
grep searches a file (or a group of files) for a specified regular expression case matters in the matching unless the -i option is specified The -v option prints all lines not containing the pattern
Examples:
% grep Smith *.letter % grep -i smith *.letter % ps aux | grep -v root
ln:
Link files
It is often advantageous to assign multiple names to a single file. The ln command links two files or directories. Either name can be used to access the file. Examples: create fort.1 which points to input.file
% ln input.file fort.1 link the directory /usr/local/lib/X11 to /usr/lib/X11
% ln -s /usr/local/lib/X11 /usr/lib/X11
mkfifo:
The | character is used to pipe the standard output of a program to the standard input of another. mkfifo is used to create a named pipe -- the output of a program can be directed to a file, which another program can open and read. On some systems the command is: mknod p Example:
% % % % mkfifo fort.11 zcat big_file.Z >> fort.11 & mknod fort.11 p zcat big_file.Z >> fort.11 &
sort:
The sort utility sorts files based on user-defined keys. If multiple files are specified, they are first merged, then sorted as a single file. Common options:
-r
sort numerically
stty:
The stty command is used to set or change the terminal/line parameters for a UNIX session. There are over 40 parameters you may change. stty -a will show the current value of all terminal settings. The sequence ^q^jstty sane^j can often be used to return control of your terminal to you after a problem. Consult the stty man page for system-dependent options.
Nearly all UNIX systems have a compiler for the C programming language (cc) and many also have a FORTRAN compiler (f77). Common options:
-O
There are usually many system-dependent options for compilers. Consult the cc and f77 man pages for more information.
make:
Maintain programs
The make utility maintains up-to-date versions of programs. The user defines dependencies for a target program and rules to update the program based on those dependencies. If none of the dependencies have changed since the last program update, the target is not rebuilt.
Sample Makefile
# Fortran compiler options FFLAGS = -O3 # Object files needed for test.x OBJS = main.o sub.o # Link to get the executable file test.x test.x: $(OBJS) f77 $(FFLAGS) $(OBJS) -o test.x clean: rm -f $(OBJS) test.x
A shell script is a collection of UNIX commands which are executed together. Similar to .BAT files in DOS and .COM files in VMS. Shell scripts are the primary tool for combining the specialized UNIX commands to perform more complex and useful tasks. Shell scripts also allow users to make use of the simple programming languages built into the different shells.
#!/bin/csh # # Check for all processes owned by the specified # user ($1) on a set of machines # foreach comp ( sa sb sc sd se sf sg sh si sj sk ) echo $comp rsh $comp ps aux | grep $1 echo " " end