Вы находитесь на странице: 1из 45

INDEX

Sr. Practical Name Page Date Sign


No. No.
01 Basic Linux commands such ad file and directory 2-6 09/12/2016
manipulation, reduction and piping.
02 Basic filter commands such as head, tail, cat, sort, cut, grep. 7-12 23/12/2016

03 Advanced filters such as egrep, fgrep, tr, sed, awk. 13-20 06/01/2016

04 File operation commands such as split, tar, find, zip, In, 21-23 13/01/2017
chmod.
05 Basic shell scripting such as defining variables, reading user 24-28 20/01/2017
input, condition, loops, string operations, arithmetic
operations.
06 Advanced shell scripting such as environment variables, 29-31 27/01/2017
shell features, commands line arguments, file tests using
backticks.
07 Process management such as ps, jobs, nice, fg, bg, at 32-35 03/02/2017

08 Linux system administration such as user management, 36-40 10/02/2017


mounting, job control(crontab), chown, chgrp etc.

09 Linux system administration such as File Operation 41-45 17/02/2017

1
Date: 09/12/2016
Practical 1

Aim: Basic Linux commands such ad file and directory


manipulation, reduction and piping.

Command: - pwd

Syntax: - pwd

This command displays present or current working Directory. It shows the absolute path or full
path of the current directory.
Output: -

$ pwd
/home/tybsc

Command: - cd

Syntax: - cd abc

Changes to the directory name abc. With cd command we can use absolute or relative path to
reach the directory abc. Absolute path is the path which starts from / whereas the relative path is
the path which is relative to the current working directory or starts from the current working
directory. For example:

$ cd . change to current directory ( i.e Same directory)

$ cd .. change to parent directory ( i.e Move up directory one level)

Command: - mkdir
Syntax: - mkdir DIRECTORY

make or create directories. For example:

$ mkdir Images
Creates directory Images in the current directory.

$ mkdir abc xyz vijay


Creates abc, xyz and Vijay directories in the current directory.

Command: - rmdir

Syntax: - rmdir DIRECTORY

Remove the DIRECTORY. For example:

rmdir Images

2
Removes directory Images.

Command: - touch
Syntax: - touch [OPTION].[EXPRESSION].[FILE]
Creates a file if it does not exist. If the file exists then modification and access time are
changed to current or predefined values.

Options: -
-m change modification time.
-a change access time.

Output: -
$ touch emp.lst
File emp.lst is created if it does not exist. If the file emp.lst exists then its modification and
access time is changed to current time. If the modification and access time is to be changed to
some different values then use m and a options.

$ touch m 02281030 emp.lst


Modification time of above file is changed to date 28 Feb and time 10:30.

$ touch a 01261650 emp.lst


Access time of above file is changed to date 26 Jan and time 16:50 am.

Command: - cp

Syntax: -cp [OPTION]... SOURCE DEST

Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.

Options: -

-d, preserve links

-i, --interactive: prompt before overwrite

-l, --link: link files instead of copying

-r, --recursive copy directories recursively

$cp sample.txt -i /home/tybsc

$cp sample.txt -l /home/tybsc

Command: - rm

Syntax: - rm [OPTION]... FILE...

3
rm prompts the user for whether to remove the file. If the response does not begin with `y' or
`Y', the file is skipped.

Options: -

-i, --interactive: prompt before any removal

-r, -R, --recursive:remove the contents of directories recursively

For example:

$rm -i tybsc

$rm - r mp3

Command: - mv

Syntax: - mv [OPTION]... SOURCE DEST

Rename SOURCE to DESTINATION, or move files to DIRECTORY. mv takes two arguments,


the first is the file to be moved. The second argument can be new filename or the pathname of
the directory.

Options: -

-i, --interactive: prompt before overwrite

For example:

$mv i mp3 /home/song

$mv game /dev

Command: - ls
Syntax: - ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).

Options: -

-a, --all: do not hide entries starting with .

-d, --directory: list directory entries instead of contents


-i, --inode: print index number of each file

-l use a long listing format

-r, --reverse: reverse order while sorting


4
-s, --size: print size of each file, in blocks

-S sort by file size

-t sort by modification time

-m fill width with a comma separated list of entries

Redirection:

Standard Input / Output Redirection

Logically all files are organized as a continuous stream of bytes in Linux. The user never
references the physical structure of a file. To the user, all files have the same organization -- a
byte stream. Any file can be easily copied or appended to another because all files are organized
in the same way. In this sense, only one standard type exists in Linux, the byte-stream file.
Linux makes no implementational distinction between a character file and a record file, or a text
file and a binary file.

Data input at the keyboard is placed in a data stream arranged as as continuous set of bytes.
Data output from a command or program is also placed in a data stream and arranged as a
continuous set of bytes. This input data stream is referred to as the standard input, while the
output data stream is called the standard output. You can redirect this standard output stream to a
particular file with > symbol.

eg : $ cat abc.txt > xyz

The output of cat command is redirected from the screen device to a file. The redirection
operation will create the file xyz. If the file is already exists, It will be overwritten with the
data from the standard output.

Many linux commands receive data from the standard input such as file commands or any
device You can take any file contents as standard input .

eg $ cat < abc

The contents of file abc are redirected to the cat command which is responsible for
displaying the contents to the screen. We can combine both the redirections as follows:

eg $ cat < abc > xyz.

The cat command receives the input from file abc and the contents is redirected as output to
the file xyz. Hence no contents are displayed to the screen.

$ cat < history . The contents of history command are redirected to cat command. So details
of history file are displayed.
5
$ cat < history > xyz. The contents of history file is redirected as input to cat command which is
again redirected as output from cat command to xyz file.

Pipes: In many situations you may want to send the standard output of one command to another
command, not the destination file. Suppose you want to send the list of files to the printer. For
this you need two commands ie. The ls and lpr command. For this you need to take the output
of ls command and use it as input for the lpr command.

$ ls | lpr You can think of data as flowing from one command to another ( through a pipe) .
To form such a connection in Linux we use what is called as Pipe. We can combine the pipe
operation with other shell features, such as wild cards to perform specialized operations

$ ls *.c | lpr List of all files with extension c is send to printer.

$ cat abc | lpr Reads and outputs the contents of abc file and then piped to the printer.

$ sort xyz | more The sort command takes the contents of file xyz and generates a version with
each line sorted in alphabetic order. This sorted version is piped through into the more command
for display on the screen. Note that the original file xyz is not been changed or sorted. Only
the output of sort command in the standard output is sorted.

We can also use multiple pipes to get a more controlled output.

$ sort xyz | cat n | lpr The file xyz will be sorted first which will piped to cat command.The cat
command with n option then takes sorted file as its input and generates the numbered, sorted
list as its output. This numbered, sorted list is then piped to lpr command for printing.

Suppose you want to print a file with the name of its directory at the top

$ pwd | cat xyz | lpr In this case the cat command will have two arguments ie. for the
standard input (from pwd command ) and xyz (name of file). This is then piped to lpr for
printing.

$ pwd | cat xyz | lpr . This will work in the same way but with directory name at the bottom.

Commands such as sort that output a modified version of its input are refered to as filters.
Filters are often used with pipes.

$ cat pqr Suppose file pqr is not present then it will issue an error. The errors can be of all
kinds. Such errors can be stored in some file for further reference. Such as $ cat pqr >
errorfile. To add new error messages to this file we will use >> operator (for appending).

$ cat ls abc >> errorfile In this case errorfile is not overwritten but the new contents are
appended.

6
Date: 13/12/2016
Practical 2
Aim: Basic filter commands such as head, tail, cat, sort, cut, grep.

Command: - head

Syntax: - head [OPTION]... [FILE]...

Print first 10 lines of each FILE to standard output. With more than one FILE, precede each with
a header giving the file name. With no FILE, or when FILE is - read standard input.

Options: -

-c, --bytes=SIZE: print first SIZE bytes

-n, --lines=NUMBER: print first NUMBER lines instead of first 10

Output: -
$head 2 sample.txt

Hello I am here

Where are you

$head c21 cpright.txt

$head -5 abc.txt | sort r (First 5 lines of abc.txt are send to sort command)

Command: - tail
Syntax: - tail [OPTION] [FILE]

Print the last 10 lines of each FILE to standard output. With more than one FILE, precede
each with a header giving the file name. With no FILE, or when FILE is -, read standard input.

Options: -

-c, --bytes=N: output the last N bytes

-n, --lines=N: output the last N lines, instead of the last 10

Output: -
$tail 24c sample.txt

$head -4 emp.lst | tail -1

7
Command: - cat

Syntax: - cat [OPTION] [FILE]...

Concatenate FILE(s), or standard input, to standard output. It takes file names for its arguments. It
outputs the content of those files directly to the standard output (by default screen)

Options: -

-n numbering lines of the file.

-v displaying non printing characters.

Output: -
$ cat -n sample.txt

1 hello I am studing in tybsc

2 how are you

Command: - sort
Syntax: - sort [OPTION]... [FILE]...

Write sorted concatenation of all FILE(s) to standard output.

Options: -

-d It sorts the file in ascending order

-r It sorts the file in descending order

Output: -
$sort d sample.txt
Because It is the Best.

hello i am hindustani.

Hindustan will became no. 1 country in a few days.

$sort r sample.txt

$sort t | k 2 emp.lst [sorts the second field (name)]


The important sort options are:

-tchar uses delimiter char to identify fields

8
-k n sorts on nth field

-k m,n starts sort on mth field and ends sort on nth field

-k m.n starts sort on nth column of mth field

-u removes repeated lines

-n sorts numerically

-r reverses sort order

-f folds lowercase to equivalent uppercase

-m list merges sorted files in list

-c checks if file is sorted

-o flname places output in file flname

Command: - cut

Syntax: - cut [OPTION] [FILE]

Print selected parts of lines from each FILE to standard output.

Options: -

-c, --characters=LIST: output only these characters

-d, --delimiter=DELIM: use DELIM instead of TAB for field delimiter


-f, --fields=LIST: output only these fields

Output: -
$cut c 6-9 emp.lst
ABC

Xyz

$cut d | f 2,3 emp.lst


Abc| 122
Cac| 122

$cut d | f 2 emp.lst | sort r (Will display name column in descending order)

9
Command: - paste

Syntax: - paste [OPTION] [FILE]

Write lines consisting of the sequentially corresponding lines from each FILE, separated by
TABs, to standard output. With no FILE, or when FILE is -, read standard input.

Options: -

-s, --serial: paste one file at a time instead of in parallel

Output:-$paste
file1 file2
aaa| QQQ www|iii|III

aaa| WWW 111 | 444|477

Syntax: -grep [options] PATTERN [FILE...]

grep [options] [-e PATTERN | -f FILE] [FILE...]

Grep searches the named input FILEs for lines containing a match to the given PATTERN. By
default, grep prints the matching lines.

Options: -

-i, --ignore-case: Ignore case distinctions in both the PATTERN and the input files.

-l, --files=without-match option.:Suppress normal output; instead print the name of each input
file from which output would normally have been printed. The scanning will stop on the first
match.

-n, --line-number: Prefix each line of output with the line number within its input file.

-v, --invert-match: Invert the sense of matching, to select non-matching lines.

Examples:-$grep
i hello *

mydata: Hello how are you.

whether:Hello I am a student

$grep l hello *
10
mydata: Hello how are you.

whether:Hello I am a

student $grep n hello *

3 mydata: Hello how are you.

6 whether:Hello I am a
student $grep v hello *

mydata: how are you now.


whether: I am a student of tybsc

More Examples

grep is used for searching a string within the file. We can pass a search pattern or regular
expressions to the grep command Regular expression is a expression which consists of elaborate
character set which can be used for searching purpose. Examples : Let us consider a file emp.lst
which contains employee contents as follows:

2233 | a.k.shukla | g.m | sales | 12/12/52 | 6000

9876 | jai sharma | director | production | 12/03/50 | 7000


5678 | sumit chakrobarty | d.g.m. | marketing | 19/04/43 |
6000 2365 | barun sengupta | director | personnel | 11/05/47 |
7800 5423 | n.k.gupta | chairman | admin | 30/08/56 | 5400

1006 | chanchal singhvi | director | sales | 03/09/38 | 6700


6213 | karuna ganguly | g.m. | accounts | 05/06/62 | 6300
1265 | s.n. dasgupta | manager | sales | 12/09/63 | 5600

4290 | jayant choudhury | executive | production | 07/09/50 |


6000 2476 | anil aggarwal | manager | sales | 01/05/59 | 5000

6521 | lalit chowdury | directir | marketing | 26/09/45 | 8200


3212 | shyam saksena | d.g.m. | accounts | 12/12/55 | 6000
3564 | sudhir agarwal | executive | personnel | 06/07/47 |
7500 2345 | j. b. sexena | g.m. | marketing | 12/03/45 | 8000
0110 | v.k.agrawal | g.m.| marketing | 31/12/40 | 9000

11
Following commands were executed on the above file:

$ grep Agarwal emp.lst (It will display only single output as follows)

3564 | sudhirAgarwal | executive | personnel | 07/06/47 | 7500

$grep [aA]g[ar][ar]wal emp.lst (It will display the output as follows)

3564 | sudhirAgarwal | executive | personnel | 07/06/47 | 7500

0110 | v.k. agrawal | g.m. | marketing | 12/31/40 | 9500

$grep [aA]gg*[ar][ar]wal emp.lst (It will display the output as follows)

2476 | anil aggarwal | manager | sales | 05/01/59 | 5000

3564 | sudhirAgarwal | executive | personnel | 07/06/47 | 7500

0110 | v.k. agrawal | g.m. | marketing | 12/31/40 | 9500

g* --- The * refers to the immediate preceding character. In this case it will match g, gg, ggg,
gggg ( after the original g) etc. It also matches a null string.

The Regular Expression set:

Symbols Significance

* Matches zero or more occurrence of previous character

. Matches a single character

[pqr] Matches a single character p,q or r

[c1-c2] Matches a single character within c1 to c2

[^pqr] Matches a single character which is not p,q or r

^pat Matches pattern pat at the beginning of the line

pat$ Matches pattern pat at the end of the line

12
Date: 06/01/2017
Practical 3
Aim: Advanced filters such as egrep, fgrep, tr, sed, awk.

Command: - egrep

Syntax: - egrep [options] PATTERN [FILE...]

egrep [options] [-e PATTERN | -f FILE] [FILE...]

egrep searches the named input FILEs for lines containing a match to the given PATTERN. By
default, egrep prints the matching lines.

Options: -

-i, --ignore-case: Ignore case distinctions in both the PATTERN and the input files.

-l, --files=without-match option.:Suppress normal output; instead print the name of each input
file from which output would normally have been printed. The scanning will stop on the first
match.

-n, --line-number: Prefix each line of output with the line number within its input file.

-v, --invert-match: Invert the sense of matching, to select non-matching lines.

Examples: -
$egrep i hello+ f1.txt f2.txt

f1.txt: Hello how are you.

f2.txt:Hello I am a student

$egrep l hello? f4.txt f6.txt

f4.txt: Hello how are you.

f6.txt:Hello I am a student

$egrep n include+ gt.tcl gtk.cpp

3 gr.tcl:#include<stdio.h>

6 gtk.cpp: #include<conio.h>

$egrep n include+ gt.tcl gtk.cpp

13
gt.tcl: how are you now.
gtk.cpp: I am a student of tybsc

Command: - fgrep - print lines matching a pattern

Syntax: - fgrep [options] PATTERN [FILE...]

fgrep [options] [-e PATTERN | -f FILE] [FILE...]

fGrep searches the named input FILEs for lines containing a match to the given PATTERN. By
default, grep prints the matching lines.

Options: -

-i, --ignore-case: Ignore case distinctions in both the PATTERN and the input files.

-l, --files=without-match option.:Suppress normal output; instead print the name of each input
file from which output would normally have been printed. The scanning will stop on the first
match.

-n, --line-number: Prefix each line of output with the line number within its input file. -
v, --invert-match: Invert the sense of matching, to select non-matching lines.

Output:-
$fgrep i mydata /home/tybsc

gnomes: Hello how are you.

whether:Hello I am a student

$fgrep l mydata /home/tybsc

kde: Hello how are you.

whether:Hello I am a student

$fgrep n mydata /home/tybsc

3 enligtenment: Hello how are you.

6 whether:Hello I am a student

$fgrep v mydata /home/tybsc

sawfish: how are you now.

whether: I am a student of tybsc


14
egrep : It offers all the features offered by grep, but its most useful feature is the facility
to specify more than one pattern for search. Each pattern is separated by | (pipe) symbol.

$egrep sengupta|dasgupta emp.lst (It will display the output as follows)

2365 | barun sengupta | director | personnel | 11/05/47 | 7800

1265 | s.n. dasgupta | manager | sales | 12/09/63 | 5600

$egrep (sen|das)gupta emp.lst (It will display the above same output)

If we want to search more than two patterns then we should pass then as a file

$egrep f pat.lst emp.lst

( where pat.lst consists of admin|accounts|sales. No new line allowed)

$egrep i agg?[ar]+wal emp.lst ( -i is used for ignoring case while matching. Since this
expression uses some characters not used by the shell at all, it can never expand into a filename.
So in the above example you can safely leave out the quotes).

The above two examples will give appropriate outputs. Please check the outputs)

The Regular expression set used by egrep is as follows :

Expression Significance

ch+ Matches one or more occurrences of character ch

ch? Matches zero or one occurrence of character ch

exp1|exp2 Matches expression exp1 or exp2

(x1|x2)x3 Matches expression x1x3 or x2x3

15
fgrep : fgrep like egrep accepts multiple patterns, but it doesnt accept regular expression. fgrep
is faster as compared to grep and egrep but is used for searching simple string or group of
strings. fgrep can take patterns from file using f option, but the patterns should be separated by
new line character

$fgrep f pat1.lst emp.lst (It will display appropriate output)

( where pat1.lst consists of :

admin

accounts

sales )

Some more examples :

$grep ../../50 emp.lst | sort

$grep ../../^50 emp.lst | sort

$grep ^2 emp.lst

$grep 7$ emp.lst

$grep ^[^2] emp.lst

$cut d | f 2,2 emp.lst | grep ^a

Various options for the grep family is given on page no 174 of Unix : Concepts and
Applications book written by Sumitabha Das)

Command: - tr

Syntax: - tr [OPTION]expression1 expression2

Translating Characters.

Options: -

-d deleting characters.

-s squeeing spaces.

16
Examples:-
$tr / ~ <emp.lst (All the / characters in file emp.lst will be replaced by ~ character)

$tr a-z A-Z < emp.lst (All the characters in the file emp.lst will be converted to Upper Case)

$tr A-Z a-z < emp.lst (All the characters in the file emp.lst will be converted to Lower Case)

Sed Editor:

sed 3q f1 : Prints 3 lines from file f1 and quit

sed n 1,3p f1 : Display lines 1 to 3 from file

f1 sed n $p f1 : Display last line from f1

sed n 3,4p f1 : Display third and fourth line from file


f1 sed 4,5d f1 : Delete lines 4 and 5 from file f1

sed n 4,5!p f1 : same as above

Inserting record:

Sed 1:\

> raj\

> manoj\

> sachin

> f1 > x

3 records (names) along with the contents of the file f1 are inserted into file x. To make
changes permanent to the file f1:

$ mv x f1 : ie Rename file x as f1

17
AWK :

Awk is a programming language which allows easy manipulation of structured data and the
generation of formatted reports. Awk stands for the names of its authors Aho, Weinberger,
and Kernighan

The Awk is mostly used for pattern scanning and processing. It searches one or more files to see if
they contain lines that matches with the specified patterns and then perform associated actions.

Some of the key features of Awk are:

Awk views a text file as records and fields.


Like common programming language, Awk has variables, conditionals and loops
Awk has arithmetic and string operators.
Awk can generate formatted reports

Syntax:

$ awk '/search pattern1/ {Actions}


/search pattern2/ {Actions}' file

In the above awk syntax:

search pattern is a regular expression.


Actions statement(s) to be performed.
several patterns and actions are possible in Awk.

file Input file.


Single quotes around program is to avoid shell not to interpret any of its special
characters.

Let us create employee.txt file which has the following content, which will be used in the
examples mentioned below.

$cat employee.txt

100 Thomas Manager Sales $5,000


200 Jason Developer Technology $5,500
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000

Example 1.
$ awk '{print;}' employee.txt
100 Thomas Manager Sales $5,000
200 Jason Developer Technology $5,500
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000
18
In the above example pattern is not given. So the actions are applicable to all the
lines. Action print with out any argument prints the whole line by default. So it prints
all the lines of the file with out fail. Actions has to be enclosed with in the braces.

Example 2. Print the lines which matches with the pattern.


$ awk '/Thomas/
> /Nisha/' employee.txt
100 Thomas Manager Sales $5,000
400 Nisha Manager Marketing $9,500

In the above example it prints all the line which matches with the Thomas or Nisha. It has
two patterns. Awk accepts any number of patterns, but each set (patterns and its
corresponding actions) has to be separated by newline.

Example 3. Print only specific field.

Awk has number of built in variables. For each record i.e line, it splits the record delimited by
whitespace character by default and stores it in the $n variables. If the line has 4 words, it will
be stored in $1, $2, $3 and $4. $0 represents whole line. NF is a built in variable which
represents total number of fields in a record.

$ awk '{print $2,$5;}'


employee.txt Thomas $5,000
Jason $5,500
Sanjay $7,000
Nisha $9,500
Randy $6,000

$ awk '{print $2,$NF;}'


employee.txt Thomas $5,000
Jason $5,500
Sanjay $7,000
Nisha $9,500
Randy $6,000

Example 4. Find the employees who has employee id greater than


200 $ awk '$1 >200' employee.txt
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000

In the above example, first field ($1) is employee id. So if $1 is greater than 200, then just do the
default print action to print the whole line.

19
Example 6. Print the list of employees in Technology department

Now department name is available as a fourth field, so need to check if $4 matches with
the string Technology, if yes print the line.

$ awk '$4 ~/Technology/' employee.txt


200 Jason Developer Technology $5,500
300 Sanjay Sysadmin Technology $7,000
500 Randy DBA Technology $6,000

Operator ~ is for comparing with the regular expressions. If it matches the default action i.e
print whole line will be performed.

20
Date: 13/01/2017

Practical 4
Aim: File operation commands such as split, tar, find, zip, In, chmod.

Command: - split
Syntax: -split number filename
This command splits the file. By default it splits the file after each 1000 lines, you can specify
the pages setting i.e.72 lines
Output: -
$ split -2 sample.txt
$ ls
xaa (Names of the file which is created after splitting) xab

Command: - tar [tape Archiving Utility]

Tar : The tar utility creates archives for files and directories. Tar stands for Tape archive. It is
similar to ZIP files in windows. The command is as follows $ tar -cf abc.tar mydir ( The
contents of mydir and its sub directories are zipped to abc.tar file)

Creating an archive:

tar -cvf archive.tar *.txt [Where options c stands for create, v for verbose and f for file]

To extract the tar directories of tar files use x option. For eg

$ tar -xf abc.tar xyz ( the contents of abc.tar are extracted to file xyz)

To view the contents of abc.tar file

$ tar -tf abc.tar

$ tar -rf abc.tar jkl.c ( r option is used to add files to archive that is already created. The r option
appends the files to the archieve.

$ tar -uf abc.tar mydir ( Updates the abc.tar file with any recently modified or newly created
files in the mydir)

Command: - find [for searching Files]

Syntax: - find [PATH LIST][OPTION]... [FILE]...

Options: -
21
-name search by name of the file
-inum search by inode number of the file

Output:-
$ find / -name abc.txt
/home/vijay/abc.txt
In the above example the file abc.txt is to be searched from /
directory. $ find . inum 13957
x.txt
In the above example the file with inode number 13957 is to be searched from current
directory. (for current directory dot operator is used)

Command: - zip

Command: - gzip

Command: -bzip2

Command: - ln

Command: - chmod

Syntax: - chmod [OPTION]... MODE[,MODE]... FILE...

chmod [OPTION]... OCTAL-MODE FILE...

Description:

Each file and directory in Linux contains a set of permission that determines who can access
them and how. A file and directory may have read, write and execute permission. When a file is
created it is automatically given read and write permission for the owner enabling you to modify
and display the file. A file could also have execute permission allowing it to be executed as a
program. When ls l command is used it displays all the content of the directory in the
following format,

-rw-rw-r-- 1 tybsc tybsc 8143 Oct 30 12:01 Docs.txt

22
The first three characters of first column is for users, second group is for group and the last is
for others. Here r denotes read, w denotes write, x denotes execute.

[r,w,x are character permissions. We can also use octal permissions such as 4 for read, 2 for
write and 1 for execte]

Option: -

+ Adds a permissions
- Removes a permissions
= Assigns entire set of permissions

r Sets read permissions for a file or directory. This type of file can be read and
displayed. A directory can have list of its files displayed.

w Sets write permissions for a file or directory. This type of file can be edited and erased.
A directory can be removed.

x Sets execute permissions for a file or directory. If a file is shell script then it can
be executed as a program. A directory can be changed to and entered.

u Sets permissions for the user who created and owns the file or directory. g
Sets permissions for the group access the file or directory.
o Sets permissions for the other users on the system.
a Sets permissions for access by the user, group and all other users.

$ chmod +x-w mydata: Adding execute permission and removing write permission.

$ chmod 777 mydata: Adding all permission for all type of users(ie owner, group member and
Others)

23
Date: 20/01/2017

Practical 5

Aim: Basic shell scripting such as defining variables, reading user


input, condition, loops, string operations, arithmetic operations.

Defining variables and Reading user input:

Example1:

echo Enter the values of a,b,c


read a b c
scale = 6

echo you have entered


echo $a $b $c

echo their sum and product is


x = `echo $a + $b + $c | bc l`
y = `echo $a\*$b\*$c | bc l`
echo $x $y

Conditions:

#THIS PROGRAM DEMONSTRATES THE USE OF if


echo enter any number
read n

if test $n gt
0 then

echo $n is positive
else
echo $n is negative
fi

24
#THIS IS PROGRAM FOR IFELSE WITHOUT
TEST echo enter the basic salary

read b
scale = 2

if [$b lt 1500]
then

hra=`echo $b\*10/100|bc l`
da=`echo $b\*90/100|bc l`

else

hra=500

da=`echo $b\*98/100|bc l`

fi

g=`echo $b+$hra+$da|bc l`
echo gross salary = $g

Loops:

#Program to print first n numbers and their sum:while loop


i=1
sum=0

while [ $i le 10 ]
do
echo $i

sum=`expr $sum +
$i` i=`expr $i + 1`
done

echo The sum is= $sum


echo end of prog15
25
#Program to print first n numbers and their sum:dountil
i=1
sum=0

until [ $i gt 10 ]
do
echo $i

sum=`expr $sum +
$i` i=`expr $i + 1`
done
echo The sum is= $sum

#program: for
loop sum=0

for i in 1 2 3 4 5 6 7 8 9 10
do

sum=`expr $sum +
$i` echo $i

i=`expr $i + 1`
done
echo The sum is= $sum

#Program to print the day of the week using


casein echo Enter the day number

read num

case $num in

1) echo Sunday;;
2) echo Monday;;
3) echo Tuesday;;
26
4) echo Wednesday;;
5) echo Thursday;;
6) Friday;;
7) Saturday;;
*) echo Enter the number bet 1 to 7;;

String operations:

Comparison Description
str1 = str2 Check if str1 is the same as string
str2. str1 != str2 Check if str1 is not the same as
str2. str1 < str2 Check if str1 is less than str2.
str1 > str2 Check if str1 is greater than str2.
-n str1 Check if str1 has a length greater than
zero. -z str1 Check if str1 has a length of zero.

#PROGRAM FOR STRING COMPARISON

echo ENTER THE TWO STRINGS


read str1 str2
if [ $str1 = $str2 ]

then
echo THE STRINGS ARE IDENTICAL
else

echo STRINGS ARE NOT IDENTICAL


fi

Arithmetic operations: (using command expr)


# Program to check number is even or odd.

echo "Enter the number"


read no
k=`expr $no %
2` if test $k -eq 0
then
echo "Number is
even" else
echo "Number is odd"
fi

27
# Program to print even number series.

no=0
echo "Enter
limit" read limit
echo "Even number series"
while [ $no -le $limit ]
do
echo $no
no=`expr $no + 2`
done

28
Date: 27/01/2017

Practical 6
Aim: Advanced shell scripting such as environment variables, shell
features, commands line arguments, file tests using backticks.

Command Line Arguments:

$1,$2 The positional parameters


$* Complete set of positional parameters as a single string
$# Number of arguments specified in command line
$0 Name of executed command $?
Exit status of last command $!
PID of last background job
$@ Same as $* except when enclosed in double quotes

# write a program to check the user is logged in or not.


clear

if [ $# -ne 1 ]
then
echo Usage : Scriptname Username
exit
fi

n=`who | grep -c $1`


if [ $n -gt 0 ]
then
echo "$1 Hello! You are login"
else
echo "$1 check!You have not logged in"
fi

29
File tests:

# Check if input filename is a file or directory if it is a directory then list the contents of
directory. If it is a file,check if it has read & write permission.

Program:-

echo "Enter file


name" read fnm

if test -f
$fnm then

echo "$fnm is an ordinary file "


if test -r $fnm
then

echo "$fnm has read


access" else
echo "$fnm has no read access"
fi

if test -w $fnm
then

echo "$fnm has write


access" else
echo "has no write access"
fi

30
if test -d $fnm
then

echo "$fnm is
directory" pwd

cd $fnm
ls -l
else
echo "$fnm is not directory"
fi

# Enter a filename and check

clear
echo Enter filename :
read file
if [ -s $file ]
then
if [ -f $file ]
then
echo "--------------------------------------"
cat $file
echo "--------------------------------------"
elif [ -d $file ]
then
ls -i $file
fi
else
echo "This file is empty"
fi

Backticks:

# Write a shell script to find which user login first


time. x=`who|cut -c25-30 |sort|head -1`
name=`who|grep $x|cut -f1 -d" "`
echo The first login person is $name
-----------------------------------------------------
echo "The value of variable x is $x"
x=20
echo "The value of the variable x is $x"
31
Date: 03/02/2017

Practical 7
Aim:- Process management such as ps, jobs, nice, fg, bg, at

ps: ps gives a snapshot of the current processes. If you want a repetitive update of this status,
use top.

Example:

ps -au | less

The -a option tells ps to list the processes of all users on the system rather than just those of
the current user. The -u option tells ps to provide detailed information about each process. less
command is used to view the output one screenful at a time.

jobs: Background, Kills and Interuptions

You can run a job in the background while you execute other commands.

You can even interrupt a command, starting it again later from where you left off. Background
operations are particularly useful for long jobs. Instead of waiting at the terminal until a
command has finished execution, you can place it in the background. eg. Edit a file while
others files are printing.

You execute a command in the background by placing an ampersand on the command line at
the end of the command

$ lpr abc &

Output : [1] 534

User Job No. System Process No.

You can place more than one job in the background

$ lpr abc $

Output : [1] 547

$ cat *.c > xyz &

Output : [2] 548

$ jobs

32
Output : [1] + Running lpr abc

[2] - Running cat * .c > xyz

If you wish, you can several commands at once in the background

$ sort *.c > pqr & ; lpr *.c & $


jobs

Output : [1] + Running sort *.c > pqr

[2] - Running lpr *.c

When a job in the background completes the system will not notify you about the completed job.
Ie. It will not disturb you. Butif you want to be notified immediately when a certain job ends, no
matter what you are doing on the system you can use notify command

$ notify % 2 It will notify you when job 2 has finished

To bring a job in the foreground use $ fg command

$ fg % 2 . You may not immediately receive the prompt again because the command is now in
the foreground and might be executing.

If you want to stop a job in the background, you can force it to end with the kill command

$ kill % 2 You can stop a job by passing job no as parameter to kill

$ kill 548 Or by passing system process no.

To check all the ongoing system process use $ ps

Output : PID TTY TIME COMMAND

523 tty24 0:05 sh

567 tty24 0:01 lpr

570 tty24 0:00 ps

Process id PID Or

System process no Terminal identifier Time taken by the process

33
You can suspend a job by using ctrl + z keys. This places a job to the side until it is restarted.
The job is not ended but it merely remains suspended until you want to continue. When you
want to continue with the suspended job use fg or bg. The fg command restarts a suspended job
in the foreground. The bg command places the suspended job in the background.

$ cat *.c > pqr

^z The job is suspended

To restart a job in background mode, use the bg command, along with the job number:

$ bg 2 The job is restarted and placed in the background where 2 is job no.

nice:

With the help of Nice command in Linux you can set process priority. If you give a process
a higher priority, then Kernel will allocate more cpu time to that process.

By default when a programe is launched in Linux, it gets launched with the priority of '0'.
However you can change the priority of your programes by either of the following methods.

1. You can launch a program with your required priority.


2. Or you can also change the priority of an already running process.

For example

nice n 10 <command name> Will set a process with the priority of "10".

Process priority values range from -20 to 19.

A process with the nice value of -20 is considered to be on top of the priority. And a process
with nice value of 19 is considered to be low on the priority list.

renice:

In order to change the priority of an already running process you can use "renice" command.

For example

$ renice 10 -p 29504 [this will set the priority of process id no 29504 to 10]

29504: old priority 0, new priority 10

Scheduling a job using the at, batch commands

34
at:

The at command format


The basic at command format is pretty simple:

at [-f filename] time

By default, the at command submits input from STDIN to the queue. You can specify a
filename used to read commands (your script file) using the -f parameter.
The time parameter specifies when you want the Linux system to run the job. You can get
pretty creative with how you specify the time. The at command recognizes lots of different time
formats:
1. A standard hour and minute, such as 10:15
2. An AM/PM indicator, such as 10:15PM
3. A specific named time, such as now, noon, midnight, or teatime (4PM)
If you specify a time thats already past, the at command runs the job at that time on
the next day.
Besides specifying the time to run the job, you can also include a specific date, using a few
different date formats:
1. A standard date format, such as MMDDYY, MM/DD/YY, or DD.MM.YY
2. A text date, such as Jul 4 or Dec 25, with or without the year
3. You can also specify a time increment:
a) Now + 25 minutes
b) 10:15PM tomorrow
c) 10:15 + 7 days

examples :

$ at -f test5 10:15
warning: commands will be executed using /bin/sh
job 7 at 2007-11-04 10:15

$ at -f test5 4PM
warning: commands will be executed using /bin/sh
job 8 at 2007-11-03 16:00

batch:

The command format for the batch command is:

batch [-f filename] [time]

You can use the -f parameter to specify a file to read commands from. You can also optionally
specify the earliest time that the batch command should try running the job.

35
Date: 10/02/2017
Practical 8

Aim:- Linux system administration such as user management,


mounting, job control(crontab), chown, chgrp etc.

Logging on to LINUX: You can log into Linux from GUI mode or Command Line mode. You
will be prompted for login name and password. You can work as Administrator or a Normal
user. It is always advised to work as Normal user. Administrator account is used for special
purposes such as doing maintenance work, creating users, changing passwords etc., Use login
name as root and password (which is given during installation) to work as Administrator. The
login name and password is validated, and if found ok, you are allowed to enter and you are
taken directly to your home directory.
Logging out of Linux: To log out use the command exit.
Creating user accounts: To create users use the command useradd or adduser.

Command: - useradd
Syntax: - useradd accountname
Eg. useradd Vijay

Options: - There are many options, which can be used along with useradd command. These
options can be found from man pages.
By default the command creates Vijay directory under /home. This directory is the
home directory for the user Vijay.

To give password to newly created account the command is passwd.

Command: - passwd
Syntax: - passwd accountname
Eg. passwd Vijay
For Password Framing Rules and Discipline or Changing password refer to
Unix Concepts and Applications by Sumitabh Das (From Third Edition page no 50 and 51)

Study the following commands along with their important options:


tput clear, clear, ps, whatis, and man.

Command: - who
Syntax: - who [OPTION]

Options: -

-u displays the information about each connected user such as from where they have logged in
and how long they have been inactive.

36
Output: -
$ who -u

root console Nov 12 10:34 . 1219

tybsc tty1 Nov 12 12:22 10 1492

Try the following commands: whoami and who am i.

Job control(crontab):

crontab: For commands that need to be executed repeatedly (e.g., hourly, daily, or weekly), you
can use the crontab command. The crontab command creates a crontab file containing commands
and instructions for the cron daemon to execute. You can use the crontab command with the
following options:

crontab -a Install filename as your crontab file. On many systems, this command is
filename executed simply as crontab filename (i.e., without the -a option).
crontab -e Edit your crontab file, or create one if it doesn't already exist.
crontab -l Display your crontab file.
crontab -r Remove your crontab file.

Each entry in a crontab file consists of six fields, specifying in the following order:

minute(s) hour(s) day(s) month(s) weekday(s) command(s)

The fields are separated by spaces or tabs. The first five are integer patterns and the sixth is
the command to execute. The following table briefly describes each of the fields:

Field Value Description


minute 0-59 The exact minute that the command sequence executes
hour 0-23 The hour of the day that the command sequence executes
day 1-31 The day of the month that the command sequence executes
month 1-12 The month of the year that the command sequence executes
weekday 0-6 The day of the week that the command sequence executes (Sunday = 0,
Monday = 1, Tuesday = 2, and so forth)
command Special The complete sequence of commands to execute. The command string must
conform to Bourne shell syntax. Commands, executables (such as scripts), or
combinations are acceptable.
37
Creating groups: To create a group we use the following command

$ groupadd computer A group named computer will be created To

create a user and add it to a group

$ useradd g computer nitin

To add a existing user to a group


$ usermod g computer sachin

To change owner of the file : Use chown command

$ ls l abc

-rw-r--r-- 2 vijay computer 300 Jan 18 12:10 abc

$ chown jay abc

The $ ls l abc will show following output

-rw-r--r-- 2 jay computer 300 Jan 18 12:10 abc

To change group for the files: To change a group for any file we use the following
command $ chgrp college abc

The $ ls l abc will give following output

-rw-r--r-- 2 jay college 300 Jan 18 12:10 abc

The chgrp command takes its first argument the name of the new group followed by name of file
( or names of files) for which the group has to changed.

We can combine the chgrp operation in the chown command


as $ chown manoj : tybsc abc

The $ ls l abc will give following output


-rw-r--r-- 2 manoj tybsc 300 Jan 18 12:10 abc

38
Some essential Administrative Commands:

Data Blocks:

All file data are stored in the data blocks, which occupy most of the file system. Block size
in Unix is 512 bytes (1024 in Linux). To find out the disk usage we use commands such as du
and df (check man du and man df)

du:

df:

fdisk:

fdisk is used to create partitions. To check partitions of the hard disk use

$ fdisk /dev/hda

The m command of fdisk show all its internal commands

Creating File system:

Newly created partitions are useless unless it contain some file system. mkfs command is used
to create file system.

$ mkfs t ext3 /dev/hda3 $


mkfs t msdos /dev/hda2

where t is used to specify the type of file system.

File system mounting:

mount command is used to mount file system (can be hard disk, floppy disk etc) as

$ mount t ext2 /dev/hda3 /mnt/cdrom

where t is used to specify the type of file system (here it is ext2) and cdrom is the
mount point (can be any directory)

$ mount t msdos /dev/hda1 /abc

To unmount use umount command

$ umount /mnt/cdrom

$ umount /abc

39
File System Checking:

Due to any problems the file system becomes inconsistent for eg If power goes off before
the superblock is written to the disk, the file system loses its integrity. There are many events
that can lead to file system corruption, and the most common ones are listed below:

1. Two or more nodes claiming the same disk block


2. A block marked as free but not listed in the superblock
3. A used block marked as free
4. A corrupt superblock containing wrong summary data.

fsck command is used to check and repair the damaged file system. It will phase wise
check all the above problems and try to fix them.

$ fsck Check All file systems ie entire hard disk

$ fsck /dev/hda1 Check only one partition

Startup and Shutdown:

During system start up the most important process, which is started by the system, is the
init process. Its process id is 1. It is responsible for starting of all subsequent processes. Init
can be started with different run levels (init 0, init 1 etc) as follows:

0. System shutdown
1. System administration mode or Single user mode (used for maintainance of the system by
the administrator)
2. Multiuser mode (Networking not available)
3. Multiuser mode (With Networking)
4. Not used currently
5. Full graphical mode (Along with networking)
6. Shutdown and Reboot mode.

So when we execute the command $ init 5 it means that all the services which are required
for graphical and networking interface should be started and so.

40
Date: 17/02/2017

Practical no.9
Write and execute the commands for the following:
i. Display /usr/sbin beginning with a lowercase c.
ii. Display and count all the lines in the file /etc/mime.types
iii. To find out how many files are in the /usr/bin directory.

i Display /usr/sbin beginning with a lowercase c.


Output:

ii. Display and count all the lines in the file /etc/mime.types
Output:

iii. To find out how many files are in the /usr/bin directory.
Output:

Construct the commands and execute them to


i. Create a file named fsp<seat_no> having the listing of atleast 50 lines (e.g, listing of /usr/sbin
or /usr/bin or /etc or can create your own).
ii. Display first 2 lines of fsp<seat_no> and convert all the characters into capital letters. 41
iii. Display the last 15 lines of fsp<seat_no>.
iv. Display the lines starting with a vowel.
v. Split the file fsp<seat_no> into subparts each having at most 20 lines and display the contents
of these subparts and count the number of lines in them.
vi. Split the file fsp<seat_no> into three subparts named fspaa, fspab, fspac and display
the contents of these files and count the number of lines in them.

i. Create a file named fsp<seat_no> having the listing of atleast 50 lines (e.g, listing of /usr/sbin
or /usr/bin or /etc or can create your own).

Output:

ii. Display first 2 lines of fsp<seat_no> and convert all the characters into capital letters.

Output:

iii. Display the last 15 lines of fsp<seat_no>.

Output:
42
iv. Display the lines starting with a vowel.

Output:

v. Split the file fsp<seat_no> into subparts each having at most 20 lines and display the
contents of these subparts and count the number of lines in them.

Output:

43
vi. . Split the file fsp<seat_no> into three subparts named fspaa, fspab, fspac and
display the contents of these files and count the number of lines in them.

Output:

Output:

Output: 44
45

Вам также может понравиться