Basic Linux Info
Basic Linux Info
SYSTEM ORGANISATION
The functioning of Linux is manned in three levels 1. Tools and applications 2. Shell 3 Kernel 3. Tools and application programs which speak our language.(Programming language ) Kernel interacts with actual hardware in machine language. Th shell The h ll, or the th command di interpreter t t as it is i called, ll d i is the mediator, which interprets the commands that we give and then conveys g y them to the kernel which ultimately executes them.
2
Internet Tools
SHELL AS A INTERPRETOR
The shell is an ordinary program which interprets the commands that are typed at the terminal, and translates them into commands that are understood by the kernel. These programs are located in individual files in one of the system directories, such as /bin, /etc, or /usr/bin. The process of command interpretation by the shell can be explained as follows : reads the command searches h f for and dl locates the h fil file with i h that h name i in the h directories containing utilities. loads the utility y into memory y executes the utility
4
TYPES OF SHELLS
The Linux based shells in the freely available distributions are: Bash B h is Bash i an acronym f for Bourne B Again A i Shell Sh ll. It is i an enhancements to the Bourne shell and is the default shell for most Linux systems. In Red Hat Linux, sh is the symbolic link for the Bash shell which is stored under the /bin directory. Pdksh Pdksh stands for Public Domain Korn Shell and is an enhancement of the Korn shell. On Linux systems, ksh is the symbolic link to the Pdksh shell.
CONTINUED. CONTINUED
Tcsh Tcsh stands for Tom oms s C shell also known as the TC shell, and an enhancement of the C shell. The symbolic link available for Tcsh shell on Linux is csh csh. ASH It is i usually ll suitable it bl on machines hi th that th have very li limited it d memory.
LINUX COMMANDS
Remember a few things that apply to all Linux commands All Li Linux commands d should h ld always l b be entered t di in small case letters (case sensitive). Between the command name and the options p that may be available with the command there must always be a space or a tab. The option is usually preceded by a minus( minus(-) ) sign. sign Two or more options available with a command can usually be combined.
7
Password: ***** Once the correct login name and password have been supplied, you find some welcome messages from the suppliers of the Linux version installed on the host machine, followed by a command prompt. The command prompt is a $(dollar) if you are operating in Bash shell, or a % if in C shell.
8
10
FILE COMMANDS
11
13
cd /full/path/name/from/root changes directory to absolute path named (note the leading slash)
14
CREATING A DIRECTORY
The mkdir (make directory) command is used to create directories. Syntax mkdir [options] directory Common Options -p create the intermediate (parent) directories directories, as needed -m mode access permissions. Examples $ mkdir /home/frank/data if your present working directory is /home/frank the following would be equivalent: $ mkdir data
15
REMOVING A DIRECTORY
The rmdir (remove directory) command removes the directory specified. Syntax S t rmdir directory Examples p To remove the empty directory /home/frank/data while in /home/frank use: $ rmdir data or $ rmdir /home/frank/data
16
17
Options p of ls
Options
-a lists all files, including those beginning with a dot (. ) -l long listing: lists the mode, mode link information, information owner, owner size, last modification (time). -r We can reverse the order of the presentation. -F indicates type of entry with a trailing symbol: 9 * / 9 / 9 Nothing executable directories ordinary file
18
DISPLAYING CONTENTS
The cat (concatenate) command displays the contents of the specified file. Command/Syntax cat [options] file more (or less or pg) [options] file What it will do concatenate (list) a file page through a text file
19
DISPLAYING CONTENTS
Th The cat t command d can be b used dt to vertically ti ll concatenate t t the th contents of more than one file.
Example:
20
COPYING FILES
The cp (copy) command duplicates the contents of the source file into a target file. Syntax cp [options] <source file/s><destination directory/file> Examples $ cp old_filename new_filename
21
COPYING FILES
Common Options -i i interactive (prompt and wait for confirmation before proceeding) -r recursively copy a directory Complete path names can be specified with the cp command to copy files across directories directories.
22
REMOVING FILES
The rm( remove) command is used to delete files or directories. Syntax rm [options] filename/s Example $ rm data1 data1.txt txt
23
REMOVING FILES
Common Options 9 -i interactive (prompt and wait for confirmation before proceeding) 9 -r recursively remove a directory, first removing the files and subdirectories beneath it 9 -f f don dont t prompt for confirmation (overrides -i) i) If the file to be deleted is not located in the current or sub directories directories, the complete path name has to be given.
24
25
26
27
28
29
paste COMMAND p
Example : $ paste d$: file1 file2 file3 This will take the first line of file1 add $ to it. it Take the first line of file two and add : to it.It returns to perform the same function on all the lines of the file, till the end of file. The paste utility expands a tables width, increasing the number of columns. The cat utility expands a tables length, increasing the number of rows rows.
30
31
nl COMMAND
The nl command is used to add line numbers to a file. Th line The li numbers b records d the h relative l i position i i of f a li line i in a file. Example : $ nl hawks.c hawks c 1. #include <stdio.h> 2.int main() 3{ 3.{ 4. Printf(\nHai); 5. Return 0; 6 } 6. The i option is used to specify the value, other than the default 1, by which line numbers must be incremented.
32
WILDCARD CHARACTERS
W We may require i t to enter t a number b of f filenames fil in i the th command line. Example: $ ls -l chap chap01 chap02 chap03 chap04 chap05 The above listing all files beginning with chap. Since the filenames used here have a common string(chap), the lengthy command line, using this repeatedly, doesnt look elegant. We can have a single pattern consisting of the string chap, along with one or two special characters. g wildcard characters. The shell does this through
33
WILDCARD CHARACTERS
The shell offers the facility to perform an operation on a set of files without having to specify all the names of the files on which the operation is to be performed. This is made possible by the use of certain special characters in the command in place of the actual file names. These special characters are called wildcard ildcard characters.
34
WILDCARD CHARACTERS
The following g are the lists of wildcards available, , with a description Table. * -- Matches none or one character or a string more than one character. ? [] -- Matches exactly one character character. -- Matches exactly one of a specified set of characters. Using this, the above example can be solved by as follows $ ls l chap*
35
WILDCARD CHARACTERS
Examples: COMMAND OUTPUT $ ls a* a ab abcd ac abc abcde $ ls a? ab ac $ ls a[bcd] ab ac Suppose there are following files in present in working directory: art part part1 part2 part3 mozart tart quartz $ ls a? No output $ ls a* art $ ls *.* No such file and directory $ ls [!abc]art part tart $ ls [ [b-dpu-z]* p ] part p p part1 p part2 p part3
36
37
38
write
execute
40
Continuation..
Symbolic mode : r - read w - write x - execute u - users g - group o - others - means remove + means grant = means only those permissions (u u=rw rw means user read and write) Example : $ chmod g-r data1.C data1 C Here g means group - means read permission has been removed.
41
42
Continuation.
Example : $ chmod 764 data1.C
It means file access permission has been changed by the command chmod read, write, execute permissions for the user, read and write for the group owner, and only read for other users
43
44
LINK FILE
When a file is copied, both the original and copy occupy separate space in the disk. Linux allows a file to have more than one name, and yet maintain a ta a s single g e copy in the t e disk. d s Changes C a ges to o one e file e are also reflected in the other. The file is then said to have more than one link link, it means it has more than one name.
45
ADVANTAGES OF LINKING
If we accidentally id t ll d delete l t a fil file with ith a single i l li link k or a single i l name there is no bringing it back as Linux has no file undelete facility. If one fil file has h 2 or more li links, k our fil file i is safe f even if one of f the links gets deleted. If one file is to be shared between several users instead of f giving i i each h user a separate t copy of f the th same file fil we can create links of this file in each users directory. This avoids unnecessary duplication of the same file contents in different directories directories. The file is physically not removed until at least one link is pointing to the file.
46
47
SYMBOLIC LINK
Limitation of Hard link 9 We cant have two linked files in two file systems. In other words, if we have a file in the ext2 file system, we cant link this file to another file in the /home file system. 9 We can cant t link a directory even within the same file system. Unlike Hard Links, a symbolic link points to the file which c actua actually y has as t the e co contents te ts. We can create a symbolic link with s option of ln. 9 ln s data lndata
48
LOCATING FILES
It recursively examines a directory tree to look for files matching some criteria, and then takes some action on the h selected l d fil files. # find / -name .bash_profile print The path list ( / ) indicates that the search should start from the root directory. p the action (p (print) ) to be taken The last section specifies on the file.
50
51
COMPARING FILES
52
53
The l option : -l -- gives a detailed list of the byte number and differing Bytes in octal for each character that differs in both files. $ cmp l note1 note2 3 5 9 143 145 178 190 172 175
54
56
diff COMMAND
The diff command is another file-comparison command. It is used to compare two versions of the same file. The output is a list of editing actions that must be added to the first file in order to generate the second edited file. Editing ma may incl include, de adding a line line, deleting a line line, changing a line, and so on.
57
diff COMMAND
Example $ diff file1 file2 0a1 file >Command options 2c3,4 <system calls -> options of file > list of functions 4d5 < in the chapter.
# Append after line 0 of first # this line # Change line 2 in first file # Replace this line # with # these two # lines # Delete 4 of first file # containing this line
uniq COMMAND
There may be instances where the lines in a file are duplicated. The duplicates must be removed. The uniq command is used to remove repeated lines from a file file. A file must be sorted before using the uniq command.
59
generates output in default style but with each line preceded by a count of the number of items it occurred. -n the first n fields together with any blanks before each a eac are e ignored g o ed +n the first n characters are ignored.
60
61
62
STANDARD FILES
A computer consists of mainly three parts, the input, processing, and output devices. Linux treats all input and output devices as special files. These files are categorized g as, Standard Input Files Standard Output Files Standard Error Files
63
64
Standard Output File The shell assigns the monitor as the default destination for the output of any command that it executes. The monitor is referred to as the standard output file. The file descriptor 1, is assigned to the standard output file.
65
Standard Error File Shell utilities display error messages on the monitor. The monitor is thus also the standard error file. File descriptor 2, is assigned to the standard error file.
66
REDIRECTION
Redirection changes the assignments for the standard input, standard output, and the standard error. The three types of redirection are: Input redirection Output redirection Error redirection
67
INPUT REDIRECTION
The following example illustrates the usage of input redirection: $ cat < test1 Here, the less than symbol, <, implies input redirection from the file, test1. The cat command will take each line of f the th file, fil t test1, t1 as input i t and d di display l it on th the monitor. it For better clarity, the above command can also be written using the file descriptor as: $ cat 0< test1 Here, 0 indicates input redirection.
68
OUTPUT REDIRECTION
The following example illustates the usage of output redirection: $ cat test1 > test2 Here, the greater than symbol, >, implies redirection of output to the file, test2. The output of the cat command is written itt t to a di disk k fil file, t test2. t2 However, if the file already exists, its contents are deleted before the output is written to it. If you want to append the output to the file, test2, the command is: $ cat test1 >> test2
69
ERROR REDIRECTION
The following example illustrates the usage of error redirection: $ cat test 2> 2 error error-mesg mesg Assume that the file, test, does not exist in the current directory. So a user tries to execute this command, Linux will generate an error message since the execution is unsuccessful. This error message will be written to the file named errormesg. esg Unlike the file descriptors for the standard input and standard output, the file descriptor for the standard error , is compulsory. p y file 2,
70
FILTERS
A filter is a program that takes its input from the standard input file, processes( or filter) it, and sends its output to the standard output file. The grep filter The grep stands for globally search for regular expression and print out out. Syntax grep regular_expression [filename] regular_expression which has to be searched in the file. file name is optional ,without it grep expects standard input.
71
grep FILTER
In the grep command regular expressions are always given in quotes. quotes Example: grep New[abc] Matches any one of a set of characters. characters grep New[a-c] Matches any one of a range of characters. grep ^New[abc] ^N [ b ] The Th pattern tt following f ll i it must t occur at t the beginning of each line. grep New[^a-c] The pattern must not contain any character in the set specified. specified grep New[abc]$ The pattern preceding it must occur at the end of each line. grep New.[abc] N [ b ] Matches M t h any one character. h t
72
wc FILTER
The wc filter is used to count the number of lines, words, and characters in a disk file or in the standard input. Syntax wc [ [-lwc] ] [filename/s] [ ] Example: $ wc test 2
Options :
The file test has 2 lines, 7 words, 9 characters -l -- Displays the number of lines -w -- Displays the number of words -c -- Displays the number of characters
74
cut FILTER
The cut filter is useful when specific columns from the output of certain commands(such as ls, who) need to be extracted. Syntax cut [options][filename/s] Options -f<column number(s)> -- Displays the specified columns -c<character_number(S)>--Displays c<character number(S)> Displays the specified characters. -d<column_delimiter>--Specifies the column delimiter
75
cut FILTER
Example : $ cut d d : : f1 f1 /etc/passwd Here the cut command has been used to extract only the names of the users that exist in the /etc/passwd file. The field separator is a :.
76
tr FILTER
The tr filter can be used to translate one set of characters to another. This filter can also be used to squeeze repeated occurrences of a character into one. The s option is used to squeeze several occurrences of a character into one character. Example: $tr s $t s < temporary te po a y Here tr command takes input from temporary file and s option of tr works on every record, squeezing repeated spaces into a single space.
77
tr FILTER
$ tr : < /etc/passwd This command replaces all occurrences of the : : character with a space, for the file /etc/passwd and displays the output on the standard output.
78
sort FILTER
The sort filter arranges each line of the standard input in ascending order. Syntax : sort [options] [filename] if filename is not there, it will take the input from a standard input file. Options : -r -- This sorts the input in the reverse order. -f -- It arranges in the order of the ascii values of the characters. -n -- Arranges the input in ASCII sequence, numbers would also be arranged accordingly.
79
sort FILTER
Example : sort n 12 23 9 121 <ctrl>d Output: 12 121 23 9
80
The above command will display the lines in the file in sorted order. $ sort newnames oldnames The above command will display the lines in the files, newname and oldnames in a sorted order.
81
83
84
85
PIPES
Commands can be combined in such a way that the standard output of one command can be sent as standard input to another command by using pipes. Example : $ ls > tempfile $ more tempfile These two commands can be combined together by using pipes. $ ls | more
86
PIPES
The following command will display the lines containing #inlcude $ ls l | grep #include text.* To display the names of all ordinary files in the current directory, the command will be, $ ls l | grep ^- | tr s | cut d f9
87
t COMMAND tee
The intermediate output in a pipe is not saved on the disk. The intermediate output can be saved in a file using this tee command. If the file already exists, the contents of the file are overwritten. The -a option can be used to append the new contents to an existing file.
88
tee COMMAND
Example : $ cat temp | tee temp1 temp2 The above command displays the contents of the file file, temp, on the screen, and also writes to the files temp1 and temp2 $ sort numbers | tee sort-numbers | more The above command, the file, numbers is sorted, data is piped to the tee command command, which creates the file sortsort numbers, and stores the data in this file. It also sends the data as input to the more utility.
89
PROCESS STATUS
The ps command is used to display the attributes of a process. By default, default ps lists out the processes associated with a user at that terminal: $ ps PID 476 659 684 TTY tty03 tty03 tty03 TIME 00:00:01 00:00:01 00:00:00 CMD login sh ps
90
OPTIONS OF ps
The options: a Lists out the p processes of all users, but doesnt display the system processes. -u We can know the activities of a particular user. -e Lists out all the system processes.
91
93
sh died on logging out, but not its child(sort). What the kernel has done here is to reassign the PPID of the sort process that has a PID1.
94
95
OTHER UTILITIES
When we invoke bc ( (calculator) ) without arguments, the input has to be keyed in each line terminated by pressing <enter>. After you have finished your work use <ctrl+d>. $ bc 12 + 5 17 ibase=2 11001010 202 # output in decimal, I.e., base 10 <ctrl+d> # To come out of calculator $ factor 28 # input given by the user 7 2 <ctrl +d>
98
99
THE vi i EDITOR
A vi session begins by invoking the command vi with (or without) a filename: When we open a file with vi, the cursor is positioned at the top left-hand corner of the screen. We are said to be in the command mode. To enter text, you have to leave the command mode and enter the input mode. We have to save our file or switch to editing another file. Commands Co a ds can ca be entered e te ed in t the e last ast line eo of t the e sc screen ee to act on text. This mode is known as ex mode or line mode.
100
INPUT MODE
After opening the file, the user is in command mode, if you press i insert r or R replace If you want tt to switch it h back b k to t command d mode d or ex mode d from insert mode press esc key. After pressing i or r , you can type the content of the file file. This text goes into a place in memory known as buffer.
101
BLOCK COMMANDS
T To be b able bl t to use bl block k commands d we must t remember b t two things: 1. All the block commands work in ex command mode. mode 2. Line numbers should be associated with the text before we issue any block commands. To set the line numbers, , in the ex mode, , type yp set number and press enter. :nd Deletes nth line :m,n,d Deletes lines from m to n :m,n,w>>filename Appends lines m to n to a file :r filename Reads the contents of the filename at current cursor position.
103
SYSTEM ADMINISTRATION
106
RUNLEVELS IN LINUX
init is responsible for keeping the system in different states, also called runlevels. Each run level is normally a single digit(0 to 6). Normally the system t would ld b be i in any one of f th these run l levels: l 0 System shutdown 1 System administration mode 2 Full multi user state 3 Network multiuser 4 User defined 5 Shut down same as 0 6 Shutdown and reboot mode
108
110
111
112
The t option p includes the above output, p , as well as the total amount of disk space in the file system.
113
DISK USAGE
The du (disk usage) command reports usage by a recursive examination of the directory tree. This Thi i is h how du d lists li t the th usage of f /home/sales/perfect /h / l / f t # du /home/sale/perfect 156 /home/sale/perfect/forms 534 /home/sale/perfect/data 1234 /home/sale/perfect/reports By default, du lists the usage of each sub-directory of its argument, and finally produces a summary.
114
115
cpio p COMMAND
Backing Up Files -o option is used to create an archive, which can then be redirected to a device file. This is how you copy files in the current directory to a 1.44MB floppy # ls | cpio ov > /dev/fd0 Restoring Files A complete archive or selected files can be restored with the i key option. To restore all the files that were backed up with a previous cpio command the shells shell s redirection operator(<) must be used to take input from the device. # cpio iv < /dev/fd0
120
tar COMMAND
tar not only creates archives on tapes, but supports floppies as well . Exclusive features It doesnt use standard input to obtain its file list. tar accepts file and directory names as arguments. It copies one or more entire directory trees trees, i i.e., e it operates recursively. It can create several versions of the same file in a single archive. archive It can append to an archive without overwriting the entire archive.
121
fdisk IN LINUX
fdisk in Linux creates both partitions as well as file systems. # fdisk The options: -d delete a partition -l list known partition types -m print this menu -n add a new partition -p print the partition table -q quit without saving changes -w write table to disk and exit
123
124
mount COMMAND
To mount(i.e., (i e attach) a file system system, an empty directory (say /mnt) must first be made available in the main file system. # mount t t ext2 /dev/fd0 /mnt/floppy
/dev/fd0 loses its separate identity. It now becomes the directory /mnt/floppy The type of file system is specified with the t option. If you are not specifying a file sytem it assumes the file system should be vfat filesystem.
125
126
127
128
129
PRINT COMMANDS
Print commands allows us to print files to standard output t t or to t a line li printer. i t Following are the commands to submit, cancel, and check the status of a print job. Command/Syntax lpq (lpstat) [options] lpr (lp) [options] lprm (cancel) [options] What it will do show the status of the print jobs file print to defined printer remove a print job from the print queue.
130
Shell Programming
131
SHELL PROGRAMMING
Why y we need shell p programming? g g 1. Customizing your work environment. 2. Automating your daily tasks. 3. Automating repetitive tasks. 4. Executing important system procedures like shutting down the system. 5. Performing g the same operation p on many y files. In the shell programming we have to add, 1. #!/bin/sh - It is a logical link to indicate the shell that it is a shell script. 2. Chmod +x filename without this we will not be able to execute to the shell script.
132
CONDITIONAL STATEMENTS
If condition1 # if conditions is TRUE=0 then th cmd list-1 elif condition2; then cmd list-2 else cmd list-n fi Ex: if [ $# -ge 2 ] then echo more than two arguments else echo no input fi
135
LOOPING (while) ( )
While [ codition ] do cmd-list [ break ] [ continue ] done Ex: E while [ $# -gt 0 ] do echo $1 shift done
# $#=$# -1
137
LOOPING(until) ( )
until loop executes till the conditions becomes false. This is the difference between while & until. until until [ condition ] do cmd list cmd-list [ break ] [ continue ] done Ex: until [ $# -le 0 ] do echo $1 shift done
138
PROGRAMMING TOOLS
139
140
QUICK OVERVIEW
Example: // filename: hello.c hello c #include <stdio.h> int main() { printf(\nHello World!); return 0; } The gcc compiler must generate an object file from this source code. The object file is essentially the machine code equivalent of the C source. It contains code to set up the main() calling stack, stack a call to printf() function, and code to return the value of 0.
141
gcc ( g (continuation..) )
Linker has to link the object file to produce an executable. The job of the linker is to take object files, merge them with code from libraries, and produce an executable. First and foremost, the code for printf() must be linked in. Where does the code for printf() come from? Answer: Libraries A library is essentially a collection of many object files, including an index. When searching code for the printf(), the linker looks at the index for each library library. It finds the object file containing the printf() function and extracts that object file and links it to the executable.
142
143
144
SHARED LIBRARIES
Virtually all programs are linked against one or more libraries. Any program that uses a C function (such as printf or malloc ) will be linked against the C runtime library. In each of these cases, you must decide whether to link the library statically or dynamically. If you choose h t to li link k statically, t ti ll your programs will ill b be bi bigger and harder to upgrade, but probably easier to deploy. If you link dynamically, your programs will be smaller, easier to upgrade, but harder to deploy.
145
ARCHIVE
An archive (or static library) is simply a collection of object files stored as a single file. You can create an archive using the ar command.Archive files traditionally use a .a extension rather than the .o extension used by ordinary object files. Heres how you would combine test1.o and test2.o into a single libtest.a archive: $ar cr libtest.a test1.o test2.o The cr flags tell ar to create the archive. Now you can link with this archive using the -ltest ltest option with gcc.
146
CONTINUATION
Position-Independent Code (PIC) 9 PIC stands for position-independent code. The functions in a shared library may be loaded at different addresses in different programs, so the code in the shared object must not t depend d d on th the address dd ( (or position) iti ) at t which hi h it i is loaded. Combine the object files into a shared library, like this: $ gcc -shared -fPIC -o libtest.so test1.o test2.o The -shared option tells the linker to produce a shared library rather than an ordinary executable. Shared libraries use the extension .so , which stands for shared object. For Static archives and Shared libraries, , the filename always y begins with lib to indicate that the file is a library.
148
149
150
MAKEFILES
Why do we need makefiles? gcc o output hello.c hello1.c gcc command in the above example, g p , would recompile p each source file in turn before linking the executable. This can be a large waste of time, especially if you only made modifications to a single source file since last compilation.There would be no reason to recompile the other source files. To overcome this problem, makefiles are used.
151
152
make(CONTINUATION)
The above example builds a program named edime from two source files named main.c and edit.c. The command to create a executable, $ make edime The steps it follows are: gcc c main.c gcc c edit.c gcc o edime main.o edit.o If we edit main.c and reissue the command, it rebuilds only the necessary files saving us some time: gcc c main.c gcc o edime main.o edit.o g
153
154
MACROS IN MAKEFILES
When people use a filename or other string more than once in a makefile, they tend to assign it to a macro. Example: OBJECTS = main.o edit.o edime: di $(OBJECTS) gcc o edime $(OBJECTS) When make runs, runs it simply plugs in main main.o o edit edit.o o wherever you specify $(OBJECTS).
155
Thank You!!!!
156