Beijing Unix Training Beijing Unix Training Top Chai.

of 57 /57
Beijing Unix Training Beijing Unix Training Top Chai Top Chai

Transcript of Beijing Unix Training Beijing Unix Training Top Chai.

Page 1: Beijing Unix Training Beijing Unix Training Top Chai.

Beijing Unix TrainingBeijing Unix Training

Top ChaiTop Chai

Page 2: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

History of Unix, Linux, and History of Unix, Linux, and Open Source / Free Software Open Source / Free Software

Unix In 1969-1970, Kenneth Thompson, Unix In 1969-1970, Kenneth Thompson, Dennis Ritchie, and others at AT&T Bell Dennis Ritchie, and others at AT&T Bell Labs began developing a small operating Labs began developing a small operating system on a little-used PDP-7 system on a little-used PDP-7

Linux In 1991 Linus Torvalds began Linux In 1991 Linus Torvalds began developing an operating system kernel, developing an operating system kernel, which he named ``Linux'' which he named ``Linux''

Free Software In 1984 Richard Stallman's Free Software In 1984 Richard Stallman's Free Software Foundation (FSF) began the Free Software Foundation (FSF) began the GNU project GNU project

Page 3: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

UnixUnix

In 1969-1970, Kenneth Thompson, Dennis Ritchie, and In 1969-1970, Kenneth Thompson, Dennis Ritchie, and others at AT&T Bell Labs began developing a small others at AT&T Bell Labs began developing a small operating system on a little-used PDP-7. The operating operating system on a little-used PDP-7. The operating system was soon christened Unix, a pun on an earlier system was soon christened Unix, a pun on an earlier operating system project called MULTICS. In 1972-1973 the operating system project called MULTICS. In 1972-1973 the system was rewritten in the programming language C, an system was rewritten in the programming language C, an unusual step that was visionary: due to this decision, Unix unusual step that was visionary: due to this decision, Unix was the first widely-used operating system that could was the first widely-used operating system that could switch from and outlive its original hardware. Other switch from and outlive its original hardware. Other innovations were added to Unix as well, in part due to innovations were added to Unix as well, in part due to synergies between Bell Labs and the academic community. synergies between Bell Labs and the academic community. In 1979, the ``seventh edition'' (V7) version of Unix was In 1979, the ``seventh edition'' (V7) version of Unix was released, the grandfather of all extant Unix systems.released, the grandfather of all extant Unix systems.

Page 4: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

UnixUnix

After this point, the history of Unix becomes somewhat After this point, the history of Unix becomes somewhat convoluted. The academic community, led by Berkeley, convoluted. The academic community, led by Berkeley, developed a variant called the Berkeley Software developed a variant called the Berkeley Software Distribution (BSD), while AT&T continued developing Unix Distribution (BSD), while AT&T continued developing Unix under the names ``System III'' and later ``System V''. In under the names ``System III'' and later ``System V''. In the late 1980's through early 1990's the ``wars'' between the late 1980's through early 1990's the ``wars'' between these two major strains raged. After many years each these two major strains raged. After many years each variant adopted many of the key features of the other. variant adopted many of the key features of the other. Commercially, System V won the ``standards wars'' Commercially, System V won the ``standards wars'' (getting most of its interfaces into the formal standards), (getting most of its interfaces into the formal standards), and most hardware vendors switched to AT&T's System V. and most hardware vendors switched to AT&T's System V. However, System V ended up incorporating many BSD However, System V ended up incorporating many BSD innovations, so the resulting system was more a merger of innovations, so the resulting system was more a merger of the two branches. The BSD branch did not die, but instead the two branches. The BSD branch did not die, but instead became widely used for research, for PC hardware, and for became widely used for research, for PC hardware, and for single-purpose servers (e.g., many web sites use a BSD single-purpose servers (e.g., many web sites use a BSD derivative).derivative).

Page 5: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

LinuxLinux

In 1991 Linus Torvalds began developing an In 1991 Linus Torvalds began developing an operating system kernel, which he named operating system kernel, which he named ``Linux'' [Torvalds 1999]. This kernel could be ``Linux'' [Torvalds 1999]. This kernel could be combined with the FSF material and other combined with the FSF material and other components (in particular some of the BSD components (in particular some of the BSD components and MIT's X-windows software) to components and MIT's X-windows software) to produce a freely-modifiable and very useful produce a freely-modifiable and very useful operating system. This book will term the kernel operating system. This book will term the kernel itself the ``Linux kernel'' and an entire itself the ``Linux kernel'' and an entire combination as ``Linux''. Note that many use the combination as ``Linux''. Note that many use the term ``GNU/Linux'' instead for this combination.term ``GNU/Linux'' instead for this combination.

Page 6: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

LinuxLinux

In the Linux community, different organizations have In the Linux community, different organizations have combined the available components differently. Each combined the available components differently. Each combination is called a ``distribution'', and the organizations combination is called a ``distribution'', and the organizations that develop distributions are called ``distributors''. Common that develop distributions are called ``distributors''. Common distributions include Red Hat, Mandrake, SuSE, Caldera, distributions include Red Hat, Mandrake, SuSE, Caldera, Corel, and Debian. There are differences between the various Corel, and Debian. There are differences between the various distributions, but all distributions are based on the same distributions, but all distributions are based on the same foundation: the Linux kernel and the GNU glibc libraries. foundation: the Linux kernel and the GNU glibc libraries. Since both are covered by ``copyleft'' style licenses, changes Since both are covered by ``copyleft'' style licenses, changes to these foundations generally must be made available to all, to these foundations generally must be made available to all, a unifying force between the Linux distributions at their a unifying force between the Linux distributions at their foundation that does not exist between the BSD and AT&T-foundation that does not exist between the BSD and AT&T-derived Unix systems. This book is not specific to any Linux derived Unix systems. This book is not specific to any Linux distribution; when it discusses Linux it presumes Linux kernel distribution; when it discusses Linux it presumes Linux kernel version 2.2 or greater and the C library glibc 2.1 or greater, version 2.2 or greater and the C library glibc 2.1 or greater, valid assumptions for essentially all current major Linux valid assumptions for essentially all current major Linux distributionsdistributions

Page 7: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Free Software FoundationFree Software Foundation

In 1984 Richard Stallman's Free Software Foundation In 1984 Richard Stallman's Free Software Foundation (FSF) began the GNU project, a project to create a free (FSF) began the GNU project, a project to create a free version of the Unix operating system. By free, version of the Unix operating system. By free, Stallman meant software that could be freely used, Stallman meant software that could be freely used, read, modified, and redistributed. The FSF successfully read, modified, and redistributed. The FSF successfully built a vast number of useful components, including a built a vast number of useful components, including a C compiler (gcc), an impressive text editor (emacs), C compiler (gcc), an impressive text editor (emacs), and a host of fundamental tools. However, in the and a host of fundamental tools. However, in the 1990's the FSF was having trouble developing the 1990's the FSF was having trouble developing the operating system kernel [FSF 1998]; without a kernel operating system kernel [FSF 1998]; without a kernel their dream of a completely free operating system their dream of a completely free operating system would not be realizedwould not be realized. .

Page 8: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Introduction to the UnixIntroduction to the Unix

Unix is made up of three parts:Unix is made up of three parts: Kernel (Kernel (核心核心 ))

Hub of the operation systemHub of the operation system Allocate time and memory to programsAllocate time and memory to programs Handles filestore (disk) and communications (Handles filestore (disk) and communications ( 通讯通讯 )) in response in response

to system calls.to system calls. ShellShell

Interface between user and kernel (Interface between user and kernel ( 作业系统与使用者的界面:与作作业系统与使用者的界面:与作为命令处理器的操作系统一起运行的程序,用于使命令进入并使运行初始为命令处理器的操作系统一起运行的程序,用于使命令进入并使运行初始化化 ))

Command line interpreter (CLI). Interprets user commands and Command line interpreter (CLI). Interprets user commands and arranges for them to be executed. Shell types: Bourne shell(sh), arranges for them to be executed. Shell types: Bourne shell(sh), C shell(csh), Korn shell(ksh), bash shell (bash), etcC shell(csh), Korn shell(ksh), bash shell (bash), etc

ProgramsPrograms

Page 9: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Illustration of shell and kernel Illustration of shell and kernel correlationcorrelation

Suppose a user types “rm myfile”. The shell Suppose a user types “rm myfile”. The shell searches the path for the file containing the searches the path for the file containing the program rm, and then requests the kernel, program rm, and then requests the kernel, through system calls, to execute “rm” on through system calls, to execute “rm” on myfile. When the process (myfile. When the process ( 程序程序 ) “rm myfile ) “rm myfile has finished running, the shell then returns the has finished running, the shell then returns the unix prompt and waiting for further commands.unix prompt and waiting for further commands.

Page 10: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Directory Structure(目录结构 )

Directory Description

/ Root directory of the file system.

/binUser utilities fundamental to both single-user and multi-user environments.

/bootPrograms and configuration files used during operating system bootstrap.

/dev Device nodes (hardware peripheral devices)

/etcSystem configuration files(配置文件) and scripts. Very important

/proc Process file system

/root Home directory for the root account.

/sbin

System programs and administration utilities fundamental to both single-user and multi-user environments.

/tmp

Temporary files. The contents of /tmp are

usually NOT preserved across a system reboot.

Page 11: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Directory Structure (cont’d)

Directory Description

/usrCommon user utilities, programming tools, and applications.

/varMulti-purpose log, temporary, transient, and spool files.

/var/log Miscellaneous system log files.

/var/mail User mailbox files.

/var/spoolMiscellaneous printer and mail system spooling directories.

/var/tmp

Temporary files. The files are usually preserved across a system reboot, unless /var is a

memory-based file system.

Page 12: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

File and ProcessesFile and Processes

Everything in Unix is either a file or a Everything in Unix is either a file or a process.process. A process is an executing program identified A process is an executing program identified

by a unique PID (process identifier)by a unique PID (process identifier) A file is a collection of data:A file is a collection of data:

A document (report, essay etc)A document (report, essay etc) The text of a program written in high level The text of a program written in high level

programming languageprogramming language Executable or binary fileExecutable or binary file A directoryA directory

Page 13: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Basic file management Basic file management commandscommands

Command Description

ls list files and directories

ls -a list all files and directories

mkdir make a directory

cd directory change to named directory

cd change to home directory

cd ~ change to home directory

cd .. change to parent directory

pwddisplay the path of the current directory

Page 14: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Basic file management Basic file management commandscommands

Command Description

cp file1 file2 copy file1 and call it file2

mv file1 file2 move or rename file1 to file2

rm file remove a file

rmdir directory remove a directory

cat file display content of file

more file display file content a page at a time

head file display the first few lines of a file

tail file display the last few lines of a file

grep 'keyword' file search a file for keywords

wc filecount number of lines/words/characters in file

Page 15: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Other commands or Other commands or operationsoperations

Command Description

command > file redirect standard output to a file

command >> file append standard output to a file

command < file redirect standard input from a file

command1 | command2pipe the output of command1 to the input of command2

cat file1 file2 > file0 concatenate file1 and file2 to file0

sort sort data

who list users currently logged in

passwd change current password

man <command> online manual of <command>

lpr -Pprinter psfile print postscript file to named printer

Page 16: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Displaying the contents of a Displaying the contents of a file on the screenfile on the screen

clear: clear screenclear: clear screen cat: display the contents of a file on cat: display the contents of a file on

screenscreen less: show the contents a page at a timeless: show the contents a page at a time head: show the first 10 lines of a file, head: show the first 10 lines of a file,

head -5 show the first 5 lines of a filehead -5 show the first 5 lines of a file tail: show the last 10 lines of a file, tail -tail: show the last 10 lines of a file, tail -

15 show the last 15 lines of a file.15 show the last 15 lines of a file.

Page 17: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Searching the contents of a Searching the contents of a filefile

less:less: less readme.txtless readme.txt

/sigma to search for sigma in the file/sigma to search for sigma in the filen to search next occurrencen to search next occurrenceq to quitq to quit

grep:grep: grep sigma readme.txtgrep sigma readme.txt

Display each line containing the word sigmaDisplay each line containing the word sigma Case sensitiveCase sensitive

grep –i sigma readme.txtgrep –i sigma readme.txt Display each line containing the word sigma, SIGMA, …Display each line containing the word sigma, SIGMA, … Case insensitiveCase insensitive

grep –i “sigma resources” readme.txtgrep –i “sigma resources” readme.txt

Page 18: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

SortSort

Sort ASCII file only Default: sorts the file in ascending order

using the entire line as a sorting key, fields are delimited by blanks

Commonly used options: -n : sort based on numeric instead of character -r : reverse -t <char>: use char as field separater

Page 19: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

SortSort

Example: sorting passwd(4) file (user database) by UID (the third colon-separated field in the passwd structure):

sort -t ':' +2 /etc/passwd  # incorrect result, the field is numericsort -n -t ':' +2 /etc/passwd # order of the numbers is now correctps -ef | sort

This command pipeline sorts the output of the "ps -ef" command. Because no arguments are supplied to the sort command, the output is sorted in alphabetic order by the first column of the ps -ef output (i.e., the output is sorted alphabetically by username).

ls -al | sort +4nThis command performs a numeric sort on the fifth column of the "ls -al" output. This results in a file listing where the files are listed in ascending order, from smallest in size to largest in size.

ls -al | sort +4nrThis command reverses the order of the numeric sort, so files are listed in descending order of size, with the largest file listed first, and the smallest file listed last

Page 20: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

wc (words count)wc (words count)

Use this command to count the number of characters, words, and lines in a Use this command to count the number of characters, words, and lines in a file. Suppose, for example, that we have a file dict with contents file. Suppose, for example, that we have a file dict with contents red rojo red rojo green verde green verde blue azul blue azul white blanco white blanco black negro black negro % % wc dictwc dict 5 10 56 dict5 10 56 dictThis shows that dict has 5 lines, 10 words, and 56 characters. This shows that dict has 5 lines, 10 words, and 56 characters. The word count command has several options, as illustrated below: The word count command has several options, as illustrated below: % % wc -l dictwc -l dict 5 dict5 dict% % wc -w dictwc -w dict 10 dict10 dict% % wc -c dictwc -c dict 56 dict 56 dict

Page 21: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

WildcardsWildcards

ls list*ls list* List all files in the current directory starting List all files in the current directory starting

with list…with list… ls *listls *list

List all files in the current directory ending with List all files in the current directory ending with …list…list

ls ?listls ?list ls ?ouse : match files like house and mousels ?ouse : match files like house and mouse

Page 22: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

ExercisesExercises

1.1. Command displays the "/etc/passwd" file on Command displays the "/etc/passwd" file on your screen your screen

2.2. Command to combine the contents of file1, file2, Command to combine the contents of file1, file2, and file3 into file4and file3 into file4

3.3. Copies the file named "Chapter1" in the Copies the file named "Chapter1" in the "/usr/sigma" directory to the current directory "/usr/sigma" directory to the current directory

4.4. Command to provide a Command to provide a longlong listing of listing of information about information about allall files in the current files in the current directory directory

5.5. Command to display your current directoryCommand to display your current directory6.6. Copies the file named "Chapter1" in the Copies the file named "Chapter1" in the

"/usr/sigma" directory to the current directory "/usr/sigma" directory to the current directory

Page 23: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

AnswersAnswers

1.1. Command displays the "/etc/passwd" file on your screen Command displays the "/etc/passwd" file on your screen Answer: cat /etc/passwdAnswer: cat /etc/passwd

2.2. Command to combine the contents of file1, file2, and file3 Command to combine the contents of file1, file2, and file3 into file4into file4

Answer: cat file1 file2 file3 > file4Answer: cat file1 file2 file3 > file4

3.3. Copies the file named "Chapter1" in the "/usr/sigma" Copies the file named "Chapter1" in the "/usr/sigma" directory to the current directory directory to the current directory

Answer: cp /usr/sigma/Chapter1 . Answer: cp /usr/sigma/Chapter1 .

4.4. Command to provide a Command to provide a longlong listing of information about listing of information about allall files in the current directory files in the current directory

Answer: ls -alAnswer: ls -al

5.5. Command to display your current directoryCommand to display your current directoryAnswer: pwdAnswer: pwd

6.6. Copies the file named "Chapter1" in the "/usr/sigma" Copies the file named "Chapter1" in the "/usr/sigma" directory to the current directory directory to the current directory

Answer: cp /usr/sigma/Chapter1 . Answer: cp /usr/sigma/Chapter1 .

Page 24: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

File system security (access File system security (access rights)rights)

ls -l (l for long listing)ls -l (l for long listing)-rwxr-x--- 1 ksoon Users 7022 Apr 1 22:22 cygwin.ico-rwxr-x--- 1 ksoon Users 7022 Apr 1 22:22 cygwin.icodrwxrwx--- 9 ksoon Users 0 Apr 1 22:24 etcdrwxrwx--- 9 ksoon Users 0 Apr 1 22:24 etc

In the left-hand column is a 10 symbol string consisting of the symbols d, r, In the left-hand column is a 10 symbol string consisting of the symbols d, r, w, x, -, and, occasionally, s or S. If d is present, it will be at the left hand end w, x, -, and, occasionally, s or S. If d is present, it will be at the left hand end of the string, and indicates a directory: otherwise - will be the starting of the string, and indicates a directory: otherwise - will be the starting symbol of the string. symbol of the string.

The 9 remaining symbols indicate the permissions, or access rights, and are The 9 remaining symbols indicate the permissions, or access rights, and are taken as three groups of 3. taken as three groups of 3.

The left group of 3 gives the file permissions for the user that owns the file The left group of 3 gives the file permissions for the user that owns the file (or directory) (ksoon in the above example); (or directory) (ksoon in the above example);

the middle group gives the permissions for the group of people to whom the the middle group gives the permissions for the group of people to whom the file (or directory) belongs (users in the above example);file (or directory) belongs (users in the above example);

the rightmost group gives the permissions for all others. the rightmost group gives the permissions for all others.

Page 25: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

File system security (access File system security (access rights)rights)

Access rights on files.Access rights on files. r (or -), indicates read permission (or otherwise), that is, the r (or -), indicates read permission (or otherwise), that is, the

presence or absence of permission to read and copy the filepresence or absence of permission to read and copy the file w (or -), indicates write permission (or otherwise), that is, the w (or -), indicates write permission (or otherwise), that is, the

permission (or otherwise) to change a filepermission (or otherwise) to change a file x (or -), indicates execution permission (or otherwise), that is, x (or -), indicates execution permission (or otherwise), that is,

the permission to execute a file, where appropriate the permission to execute a file, where appropriate Access rights on directories.Access rights on directories.

r allows users to list files in the directory; r allows users to list files in the directory; w means that users may delete files from the directory or move w means that users may delete files from the directory or move

files into it; files into it; x means the right to access files in the directory. This implies x means the right to access files in the directory. This implies

that you may read files in the directory provided you have read that you may read files in the directory provided you have read permission on the individual files. permission on the individual files.

Page 26: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

File system security (access File system security (access rights)rights)

Example:Example:-rwx rwx rwx-rwx rwx rwx

-111 111 111 -111 111 111 a file that everyone can read, write and execute (and a file that everyone can read, write and execute (and delete).delete).

-rw- --- ----rw- --- ---

-110 000 000-110 000 000a file that only the owner can read and write - no-one else a file that only the owner can read and write - no-one else can read or write and no-one has execution rights (e.g. your can read or write and no-one has execution rights (e.g. your mailbox file).mailbox file).

Page 27: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Change access rightsChange access rights

Only the owner of a file can use Only the owner of a file can use chmodchmod to to change the permissions of a file. The options of change the permissions of a file. The options of chmodchmod are as follows: are as follows:

Symbol Meaningu userg groupo othera allr readw write (and delete)x execute (and access directory)+ add permission- take away permission

Page 28: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Change access rightsChange access rights

For example, to remove read write and For example, to remove read write and execute permissions on the file “execute permissions on the file “samplesample” ” for the group and others, type for the group and others, type % chmod go-rwx sample% chmod go-rwx sample This will leave the other permissions This will leave the other permissions

unaffected. unaffected. To give read and write permissions on the To give read and write permissions on the

file file “sample”“sample” to all, to all, % chmod a+rw sample% chmod a+rw sample

Page 29: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Chmod by the numbersChmod by the numbers

Write the permissions you want the file to have Write the permissions you want the file to have and grouped into set of three letters.and grouped into set of three letters.

For example, if you want file info.sh to have these For example, if you want file info.sh to have these permissions:permissions:– – rwx r-x r–x info.shrwx r-x r–x info.sh

Under each letter, write a digit 1; under each Under each letter, write a digit 1; under each dash write a digit zero. Ignore the dash at the dash write a digit zero. Ignore the dash at the beginning that tells you whether it’s a file or beginning that tells you whether it’s a file or directory. This gives you three binary numbers:directory. This gives you three binary numbers:- 111 101 101 info.sh- 111 101 101 info.sh

The command to change permission to above The command to change permission to above format: chmod 755 info.shformat: chmod 755 info.sh

Page 30: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Processes and JobsProcesses and Jobs

A process is an executing program identified by a A process is an executing program identified by a unique PID (process identifier).unique PID (process identifier).% ps% ps

% sleep 100 % sleep 100

(This will wait 100 seconds before returning the (This will wait 100 seconds before returning the command prompt %. Until the command prompt is command prompt %. Until the command prompt is returned, you can do nothing except wait)returned, you can do nothing except wait)

% sleep 100 & % sleep 100 &

(run (run sleepsleep in the background and returns the prompt in the background and returns the prompt straight away, allowing you do run other programs while straight away, allowing you do run other programs while waiting for that one to finish)waiting for that one to finish)

Page 31: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Backgrounding a current Backgrounding a current foreground processforeground process

At the prompt, type At the prompt, type % sleep 100 % sleep 100

You can suspend the process running in the You can suspend the process running in the foreground by holding down the foreground by holding down the [control][control] key key and typing and typing [z][z] (written as (written as ^Z^Z) Then to put it in ) Then to put it in the background, type the background, type % bg % bg

Note: do not background programs that require Note: do not background programs that require user interaction e.g. pine user interaction e.g. pine

Page 32: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Killing a processKilling a process

processes can be killed by finding their process numbers processes can be killed by finding their process numbers (PIDs) and using (PIDs) and using kill kill PID_numberPID_number

% sleep 100 &% sleep 100 &% ps% psPID TT S TIME COMMANDPID TT S TIME COMMAND

20077 pts/5 S 0:05 sleep 10020077 pts/5 S 0:05 sleep 10021563 pts/5 T 0:00 netscape21563 pts/5 T 0:00 netscape21873 pts/5 S 0:25 nedit 21873 pts/5 S 0:25 nedit

To kill off the process To kill off the process sleep 100sleep 100, type , type % kill 20077% kill 20077

type type psps again to see if it has been removed from the list. again to see if it has been removed from the list. If a process refuses to be killed, uses the If a process refuses to be killed, uses the -9-9 option, i.e. option, i.e.

type type % kill -9 20077 % kill -9 20077

Note: It is not possible to kill off other users' processes Note: It is not possible to kill off other users' processes unless you are superuser !!!unless you are superuser !!!

Page 33: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

System StatusSystem Status

whowho See who is on the systemSee who is on the system

who > names.txtwho > names.txt sort < names.txtsort < names.txt

OrOr who | sortwho | sort

Find out how many users are logged on:Find out how many users are logged on: who | wc –lwho | wc –l

dfdf Reports on the space left on the file system. For example, to Reports on the space left on the file system. For example, to

find out how much space is left on the file server, typefind out how much space is left on the file server, type % df –k . (show in kilobytes)% df –k . (show in kilobytes)

dudu Outputs the number of kilobytes used by each subdirectory.Outputs the number of kilobytes used by each subdirectory.

% du –k .% du –k .

Page 34: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

System Status (cont’d)System Status (cont’d)

psps Check the status of process that are running on your Check the status of process that are running on your

unix systemunix system ps (with no other parameters)ps (with no other parameters)

Show current running processShow current running process eg. eg. PID   TTY   TIME   CMDPID   TTY   TIME   CMD

6874  pts/9   0:00     ksh6874  pts/9   0:00     ksh6877  pts/9   0:01     csh6877  pts/9   0:01     csh418    pts/9   0:00     csh418    pts/9   0:00     csh

ps –ef (depends on unix system)ps –ef (depends on unix system) The -e and -f arguments are normally combined like this to The -e and -f arguments are normally combined like this to

show full information about every process running on the show full information about every process running on the system. system. This is probably the most often-used form of the ps This is probably the most often-used form of the ps command.command.

Page 35: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

ExercisesExercises

1.1. Command to show full information about Command to show full information about every process running on the system every process running on the system

2.2. Command to show disk usageCommand to show disk usage3.3. Command to terminate a processCommand to terminate a process4.4. How to run a program as background How to run a program as background

process?process?5.5. What is chmod 755 <file> mean?What is chmod 755 <file> mean?6.6. How to allow group to read and write on a How to allow group to read and write on a

<file>?<file>?7.7. Command to show disk freeCommand to show disk free

Page 36: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

AnswersAnswers

1.1. Command to show full information about every process Command to show full information about every process running on the system running on the system

Answer: ps -efAnswer: ps -ef

2.2. Command to show disk usageCommand to show disk usageAnswer: du –k .Answer: du –k .

3.3. Command to terminate a processCommand to terminate a processAnswer: kill <process id> or kill -9 <process id>Answer: kill <process id> or kill -9 <process id>

4.4. How to run a program as background process?How to run a program as background process?Answer: ./program &Answer: ./program &

5.5. What is chmod 755 <file> mean?What is chmod 755 <file> mean?Answer: user can read, write, execute, group can read and execute, others can read Answer: user can read, write, execute, group can read and execute, others can read

and execute.and execute.

6.6. How to allow group to read and write on a <file>?How to allow group to read and write on a <file>?Answer: chmod g+rw <file>Answer: chmod g+rw <file>

7.7. Command to show disk freeCommand to show disk freeAnswer: df –k Answer: df –k

Page 37: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

CompressionCompression

compresscompress ls –l sample.txtls –l sample.txt compress sample.txtcompress sample.txt

(the compressed file will be placed in a file called (the compressed file will be placed in a file called sample.txt.Z)sample.txt.Z)

Uncompress sample.txt.ZUncompress sample.txt.Z (the uncompressed file name will be sample.txt)(the uncompressed file name will be sample.txt)

Page 38: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

CompressionCompression

tartar Use to create compressed archives of directories and files, Use to create compressed archives of directories and files,

and also to extract directories and files from an archive. and also to extract directories and files from an archive. Initally, tar archives were used to store files conveniently Initally, tar archives were used to store files conveniently

on magnetic tape. The name ‘tar’ stands for on magnetic tape. The name ‘tar’ stands for ttape ape ararchiver.chiver. Example: Example:

% % tar -cvf foo.tartar -cvf foo.tar foofoo to compress the foo directory or foo file. to compress the foo directory or foo file.

% % tar -tvf foo.tartar -tvf foo.tar displays the file names in the compressed displays the file names in the compressed archive foo.tar archive foo.tar

% % tar -xvf foo.tartar -xvf foo.tar extracts the files. extracts the files.

Page 39: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

CompressionCompression

tartar Example: Example:

% tar -cvf foo.tar foo% tar -cvf foo.tar foo

% gzip foo.tar% gzip foo.tar (the output will be foo.tar.gz) (the output will be foo.tar.gz)

You can do above with one operation in Linux:You can do above with one operation in Linux:

% tar –zcvf foo.tar foo% tar –zcvf foo.tar foo

The output will be foo.tar.gzThe output will be foo.tar.gz

Page 40: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Command HistoryCommand History

HistoryHistory The C shell keeps an ordered list of all the commands The C shell keeps an ordered list of all the commands

that you have entered. Each command is given a that you have entered. Each command is given a number according to the order it was entered.number according to the order it was entered.

% history (show command history list)% history (show command history list) If you are using the C shell, you can use the exclamation If you are using the C shell, you can use the exclamation

character (!) to recall commands easily.character (!) to recall commands easily.% !! (recall last command)% !! (recall last command)% !-3 (recall third most recent command) % !-3 (recall third most recent command) % !5 (recall 5th command in list) % !5 (recall 5th command in list) % !grep (recall last command starting with grep) % !grep (recall last command starting with grep)

You can increase the size of the history buffer by typingYou can increase the size of the history buffer by typing % set history=100% set history=100

Page 41: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Hard Link (ln)Hard Link (ln)

Hard link is a pointer to another file with the same file Hard link is a pointer to another file with the same file contentscontents Usage: ln <actual file> <new link> Usage: ln <actual file> <new link> Commands executed upon any of these different names will then Commands executed upon any of these different names will then

operate upon the same file contents.operate upon the same file contents. The new link is not a separate copy of the old file, but rather a The new link is not a separate copy of the old file, but rather a

different name for exactly the same file contents as the old file. different name for exactly the same file contents as the old file. Consequently, any changes you make to oldfile will be visible in Consequently, any changes you make to oldfile will be visible in newlink.newlink.

After a link has been removed, the file contents will still exist as After a link has been removed, the file contents will still exist as long as there is one name referencing the file. Thus, if you use long as there is one name referencing the file. Thus, if you use the rm command on a filename, and a separate link exists to the the rm command on a filename, and a separate link exists to the same file contents, you have not really deleted the file; you can same file contents, you have not really deleted the file; you can still access it through the other link. still access it through the other link.

difficult to keep track of files. difficult to keep track of files. cannot refer to files located on different computers linked by NFS, cannot refer to files located on different computers linked by NFS,

nor can they refer to directories.nor can they refer to directories. Use symbolic link if possibleUse symbolic link if possible

Page 42: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Symbolic link (ln –s)Symbolic link (ln –s)

Symbolic link (soft link), a special kind of file that Symbolic link (soft link), a special kind of file that points to another file, much like a shortcut in points to another file, much like a shortcut in WindowsWindows ln –s <actual filename> <link filename>ln –s <actual filename> <link filename> Unlike a hard link, a symbolic link does not contain the data Unlike a hard link, a symbolic link does not contain the data

in the target filein the target file Unlike a hard link, it has ability to link to directory. This Unlike a hard link, it has ability to link to directory. This

difference gives symbolic links certain qualities that hard difference gives symbolic links certain qualities that hard links do not have, such as the ability to link to directories, links do not have, such as the ability to link to directories, or to files on remote computers networked through NFS. or to files on remote computers networked through NFS.

when you delete a target file, symbolic links to that file when you delete a target file, symbolic links to that file become unusable, whereas hard links preserve the become unusable, whereas hard links preserve the contents of the file.contents of the file.

Takes up less disk spaceTakes up less disk space Maintain one copy of file.Maintain one copy of file.

Page 43: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Environment variablesEnvironment variables

Some examples of environment variables are Some examples of environment variables are USER (your login name) USER (your login name) HOME (the path name of your home directory) HOME (the path name of your home directory) HOST (the name of the computer you are using) HOST (the name of the computer you are using) ARCH (the architecture of the computers processor) ARCH (the architecture of the computers processor) DISPLAY (the name of the computer screen to display X windows) DISPLAY (the name of the computer screen to display X windows) PRINTER (the default printer to send print jobs) PRINTER (the default printer to send print jobs) PATH (the directories the shell should search to find a command) PATH (the directories the shell should search to find a command)

ENVIRONMENT variables are set using the ENVIRONMENT variables are set using the setenvsetenv command, displayed using the command, displayed using the printenvprintenv or or envenv commands, and unset using the commands, and unset using the unsetenvunsetenv command. command.

To show all values of these variables, typeTo show all values of these variables, type% printenv | less% printenv | less

Page 44: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Unattended ScheduleUnattended Schedule

CrontabCrontab allows tasks to be automatically run in the background at regular allows tasks to be automatically run in the background at regular

intervals by the cron daemon. intervals by the cron daemon. Command:Command:

export EDITOR=vi ;to specify a editor to open crontab file.export EDITOR=vi ;to specify a editor to open crontab file.crontab -e     Edit your crontab file, or create one if it doesn't already crontab -e     Edit your crontab file, or create one if it doesn't already exist. exist. crontab -l      Display your crontab file. crontab -l      Display your crontab file. crontab -r     Remove your crontab file. crontab -r     Remove your crontab file.

*     *   *   *    *  command to be executed*     *   *   *    *  command to be executed-     -    -    -    --     -    -    -    -|     |     |     |     ||     |     |     |     ||     |     |     |     +----- day of week (0 - 6) (Sunday=0)|     |     |     |     +----- day of week (0 - 6) (Sunday=0)|     |     |     +------- month (1 - 12)|     |     |     +------- month (1 - 12)|     |     +--------- day of month (1 - 31)|     |     +--------- day of month (1 - 31)|     +----------- hour (0 - 23)|     +----------- hour (0 - 23)+------------- min (0 - 59)+------------- min (0 - 59)  

Page 45: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Unattended Schedule Unattended Schedule (cont’d)(cont’d)

A line in crontab file like below  removes the tmp files A line in crontab file like below  removes the tmp files from /home/someuser/tmp each day at 6:30PM.from /home/someuser/tmp each day at 6:30PM.

30 18  *  *  *     rm /home/someuser/tmp/* 30 18  *  *  *     rm /home/someuser/tmp/*

min hour day/month month day/week  Execution time

30 0 1 1,6,12 *00:30 Hrs  on 1st of J an, J une & Dec

0 20 * 10 1-5

8.00 PM every weekday (Mon-Fri) only in Oct.

0 0 1,10,15 * *

midnight on 1st ,10th & 15th of month

5,10 0 10 * 1

At 12.05,12.10 every Monday & on 10th of every month

:

:

\

Page 46: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Linux Linux logout, shutdownlogout, shutdown

How to exitHow to exit ::”” Logout” or CTRL-DLogout” or CTRL-D Shutdown:Shutdown:

shutdown (nowshutdown (now 、、 +mins+mins 、、 hh:ss:) -h -rhh:ss:) -h -r

halthalt

rebootreboot Virtual Console:Virtual Console:

Alt-F1, Alt-F2, Alt-F3, Alt-F4, Alt-F5, Alt-6, Alt-7 Alt-F1, Alt-F2, Alt-F3, Alt-F4, Alt-F5, Alt-6, Alt-7 (X-Windows session)(X-Windows session)

Page 47: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Useful network commandsUseful network commands

pingping telnettelnet ftpftp ifconfigifconfig route addroute add traceroutetraceroute nslookup or dignslookup or dig sshssh rshrsh serviceservice chkconfigchkconfig

xinetdxinetd mountmount

Page 48: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

chkconfigchkconfig

updates and queries runlevel information updates and queries runlevel information for system servicesfor system services

eg. eg. # chkconfig --list httpd# chkconfig --list httpd

httpd 0:off 1:off 2:off 3:off 4:off 5:off 6:offhttpd 0:off 1:off 2:off 3:off 4:off 5:off 6:off

# chkconfig httpd on# chkconfig httpd on

# chkconfig --list httpd# chkconfig --list httpd

httpd 0:off 1:off 2:on 3:on 4:on 5:on 6:offhttpd 0:off 1:off 2:on 3:on 4:on 5:on 6:off

# chkconfig httpd off# chkconfig httpd off

httpd 0:off 1:off 2:off 3:off 4:off 5:off 6:offhttpd 0:off 1:off 2:off 3:off 4:off 5:off 6:off

Page 49: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

xinetdxinetd

eXtended Internet services DaemoneXtended Internet services Daemon the only daemon process started that listens on the only daemon process started that listens on

all service ports for the services listed in its all service ports for the services listed in its configuration file. When a request comes in, configuration file. When a request comes in, xinetd starts the appropriate server. xinetd starts the appropriate server.

Some well-known services in directory listing Some well-known services in directory listing of /etc/xinetd.dof /etc/xinetd.d

chargen echo finger vsftp daytime echo-udpimap rexec telnet rlogin pop3s timersh tftp talk rsync gssftp

Page 50: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Enable telnet serviceEnable telnet service

1.1. Change disable from yes to noChange disable from yes to no2.2. Issue command: service xinetd restartIssue command: service xinetd restart

#more /etc/xinetd.d/telnet#more /etc/xinetd.d/telnet# default: on# default: on# description: The telnet server serves telnet sessions; it uses \# description: The telnet server serves telnet sessions; it uses \# unencrypted username/password pairs for authentication.# unencrypted username/password pairs for authentication.service telnetservice telnet{{ flags = REUSEflags = REUSE socket_type = stream socket_type = stream wait = nowait = no user = rootuser = root server = /usr/sbin/in.telnetdserver = /usr/sbin/in.telnetd log_on_failure += USERIDlog_on_failure += USERID disable = disable = nono}}

Page 51: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

mountmount

The mount command allows a file system to be The mount command allows a file system to be accessed.accessed.

To mount a floppy disk,To mount a floppy disk, mount /dev/fd0 /mnt/floppymount /dev/fd0 /mnt/floppy

To unmount a floppy disk,To unmount a floppy disk, umount /mnt/floppyumount /mnt/floppy

To mount a NFS file system,To mount a NFS file system, mount 10.1.1.1:/root/products /mnt/productsmount 10.1.1.1:/root/products /mnt/products

Page 52: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Vi editorVi editor

The command to start the vi editor is “vi”, followed by filename.The command to start the vi editor is “vi”, followed by filename. Two modes: command and insertTwo modes: command and insert Command mode:Command mode:

allows the entry of commands to manipulate text.allows the entry of commands to manipulate text. Insert mode:Insert mode:

puts anything typed on the keyboard into the current file.puts anything typed on the keyboard into the current file. Vi starts out in command mode.Vi starts out in command mode. From command to From command to insertinsert mode. The most commonly used commands to mode. The most commonly used commands to

get into insert mode are get into insert mode are aa and and ii. . From From insert insert to command mode, you get out of it by hitting the to command mode, you get out of it by hitting the escapeescape

key. key. Quit vi:Quit vi:

:w :w save the current file. save the current file.

:w filename :w filename save to the filename specified. save to the filename specified.

:wq :wq save and quit. save and quit.

Page 53: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Simple VI commandsSimple VI commands

a a enter enter insertinsert mode, the characters typed in will be inserted after the current cursor position. If mode, the characters typed in will be inserted after the current cursor position. If

you specify a count, all the text that had been inserted will be repeated that many times. you specify a count, all the text that had been inserted will be repeated that many times. h h

move the cursor to the left one character position. move the cursor to the left one character position. i i

enter enter insertinsert mode, the characters typed in will be inserted before the current cursor position. If mode, the characters typed in will be inserted before the current cursor position. If you specify a count, all the text that had been inserted will be repeated that many times. you specify a count, all the text that had been inserted will be repeated that many times.

j j move the cursor down one line. move the cursor down one line.

k k move the cursor up one line. move the cursor up one line.

l l move the cursor to the right one character position. move the cursor to the right one character position.

r r replace one character under the cursor. Specify replace one character under the cursor. Specify countcount to replace a number of characters to replace a number of characters

u u undo the last change to the file. Typing u again will re-do the change. undo the last change to the file. Typing u again will re-do the change.

x x delete character under the cursor. delete character under the cursor. CountCount specifies how many characters to delete. The specifies how many characters to delete. The

characters will be deleted after the cursor. characters will be deleted after the cursor.

Page 54: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

ExerciseExercise

1.1. What is the command to compresses the file What is the command to compresses the file /tmp/myfiles.tar, and /tmp/myfiles.tar, and replacesreplaces it with a file it with a file named /tmp/myfiles.tar.Z named /tmp/myfiles.tar.Z

2.2. What is the command to compress with What is the command to compress with extension tgz or tar.gzextension tgz or tar.gz

3.3. What is the operation to run a program at 3am What is the operation to run a program at 3am every day?every day?

4.4. What are the two modes available in vi editor?What are the two modes available in vi editor?5.5. Which link (symbolic link or hard link) cannot be Which link (symbolic link or hard link) cannot be

used for directory?used for directory?6.6. Which link (symbolic link or hard link) use the Which link (symbolic link or hard link) use the

smallest file size?smallest file size?

Page 55: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

AnswersAnswers

1.1. What is the command to compresses the file /tmp/myfiles.tar, What is the command to compresses the file /tmp/myfiles.tar, and and replacesreplaces it with a file named /tmp/myfiles.tar.Z it with a file named /tmp/myfiles.tar.Z

Answer: compress /tmp/myfiles.tarAnswer: compress /tmp/myfiles.tar

2.2. What is the command to compress with extension tgz or What is the command to compress with extension tgz or tar.gztar.gz

Answer: tar czvf <file.tar.gz> <file>Answer: tar czvf <file.tar.gz> <file>

3.3. What is the operation to run a program at 3am every day?What is the operation to run a program at 3am every day?Answer: crontab –e Answer: crontab –e

0 3  *  *  *     /tmp/program0 3  *  *  *     /tmp/program

What are the two modes available in vi editor?What are the two modes available in vi editor?Answer: insert mode and command modeAnswer: insert mode and command mode

1.1. Which link (symbolic link or hard link) cannot be used for Which link (symbolic link or hard link) cannot be used for directory?directory?

Answer: hard linkAnswer: hard link

2.2. Which link (symbolic link or hard link) use the smallest file Which link (symbolic link or hard link) use the smallest file size?size?

Answer: symbolic linkAnswer: symbolic link

Page 56: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

Thank youThank you !!

Page 57: Beijing Unix Training Beijing Unix Training Top Chai.

Confidential

QuestionsQuestions

Contact me: Contact me:

[email protected]@sigma-rt.com