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

Linux Programming

COMMANDS
Name

man

who

pwd
ls
ls l
mkdir
rmdir

cat

rm
cp
mv

cal

wc

more
>
cd
echo
passwd
read

head

tail

chmod

rwx

write
&&
||

Function
Manual page that displays information about
other commands.
Displays all users which are connected to the
server.
Displays the full path.
List all the files and folders .
List all the files and folders with permissions.
Makes a new directory
Removes the directory
Creates a new file.
Displays the file.
Removes the file.
Copies the file.
Moves the file.
Displays the calender of specified month and
year.
Displays the no. of lines in the file.
Displays the no. of words in the file.
Displays the no. of characters in the file.
Displays more information on the screen.
Output redirection .
Change directory.
Displays the text.
Used to change the password.
Reads a value for a variable.
Displays first n number of lines from a file.
(here n=3)
Displays last n number of lines from a file.
(here n=3)
Change the mode of the file.
Read,write and execute permission for the
users, other users in the group and users not in
the group.
Allows to send message to another user.
Executes only when both conditions are true.
Executes when any one of the conditions is true.

>>

Redirection with append.

?
[]class
[]range
[^]
{,}
vi
i
w
wq

Wildcard . helps to search the text file.


Zero or more characters.
Exactly one character.
Exactly one from the specified set.
Exactly one from the range.
Exactly one that doesnt in the range.
Exactly one of the substring .
Creates Vi editor.
Change to insert mode in vi editor
Save the file in vi editor
Save and exit the editor

Syntax
$man wc
$who
$pwd
$ls
$ls l
$mkdir dirname
$rmdir dirname
$cat> file.txt
$cat file.txt
$rm file.txt
$cp file1 file2
$mv file1 file2
$cal 10 2012
$wc l file.txt
$wc w file.txt
$wc c file.txt
$more
$ls>file1.txt
$cd dirname
$echo text
$passwd
$read text
$head n3 file.txt
$tail n3 file.txt
$chmod [option] file.txt
$chmod 457 file.sh
$write user [tty name]
$ls cal.sh && echo done:
$ls cal.sh1 || echo done:
$ls>file.txt
$who>> file.txt
$cat *.txt
$cat a?.txt
$cat a[A13].txt
$cat a[A-C 1-4].txt
$cat a[^A-C 1-3].txt
$cat a{abc,123}.txt
$vi cal.sh
Esc +i
Esc+:+w
Esc+:+w+q

q
=

Exits the editor without saving.


Assign a value to the variable.

Allows some chars to function as they behave


normally.

Never allows the functions inside the packed


area.

Delimiter

>

Standard output and standard error to


different files.

>

Standard output and standard error to same


files.

<
|

export

Export the variable as environmental variable.

set
unset
$1,$2,..
$0
$*
$#

Displays all environmental variables.


Removes the environmental variable.
Command line arguments
Filename
All argument with blank space as separator.
Total number of arguments.

if

Input redirection.
Executes many statements .
Any text from # symbol till the end of the shell
program will be ignored.

Looping statements.

STRING COMPARISON
=
- Equal to.
!=
- Not equal to.
-n
- String length greater than zero.
-z
- String length equal to zero.
NUMBER COMPARISON
-eq
- Equal to.
-ne
- Not equal to.
-lt
- Less than.
-le
- Less than or equal to.
-gt
- Greater than.
-ge
- Greater than or equal to.
FILE OPERATIONS
-s
- File exists and isnt empty.
-f
- File exists and isnt a directory.
-d
- Directory exists.

Esc+:+q
$name=sastra
$name=sastra
$echo $name
Displays
sastra
$name=sastra
$echo $name
Displays
$name
$echo Good \ morning
$ls l a*.txt 1>list.txt 2>error file
Or
$ls l a*.txt >list.txt 2>error file
$ls l a*txt >&list.txt
Or
$ls l a*.txt >list.txt 2>&1
$rev <abc.txt
$who | wc-l
#$echo name
$name = sastra
$export name
$set
$unset name
$sh file.sh text1 text2
$sh file.sh file2.sh
$if [ expression ]; then
(statements);
elif [ expression ]; then
(statements);
else (statements);
fi

-x
-w
-r

File is executable.
File is writable.
File is readable.

case

Switch between many suggestions.

if test

Can be used without []s.

function

Function can be used to reduce the program


size.

REGULAR EXPRESSION
\A
- Beginning of the letter.
\d
- Any digit.
\D
- Not a digit.
\t
- Tab.
\w
- Any word.
\W
- Not a word (i.e special characters).
\s
- White space.
\S
- Not a white space.
[]
- Character class.
[a-z]
- Single lower case.
[A-Z]
- Single upper case.
[a-z A-Z]
- Single letter.
[0-9]
- Single number.
[a-z A-Z 0- Single number or letter.
9]
[[:alnum:]] - Alpha numeric.
[[:alpha:]] - Alphabets.
[[:blank:]] - Blank .
[[:cntrl:]]
- Function keys.
[[:digit:]]
- Numbers.
[[:graph:]] - Except blank.
[[:lower:]] - Lower case.
[[:print:]] - Printable characters (non control).
[[:punct:]] - Punctuation.
[[:space:]] - White space.
[[:upper:]] - Upper case.
[[:xdigit:]] - Hexa decimal numbers.
^
- Beginning of the line.
*
- Zero or more characters.
+
- One or more characters.
Stream Editor
-a
- Append.
-c
- Change lines.
-d
- Delete lines.
-i
- Insert.
-p
- Print lines.
-s
- Substitute.

$case $var in
val1) statement;;
*)default statement;;
esac
$if test expression;then
else statement
fi
function fun_name
{
Statements
}

grep
egrep
EMAC
C-g
C-x, C-c
C-h
C-f
C-s
C-r
M-< , Chome
M-> , Cend
C-a
C-e
M-g
L-w
M-w
L-y
C-x 0

Pattern mtching.
Extension to egrep.

Cancel current command.


Exit emac.
Help area.
Load a new file.
Save current file.
Close current file.

Cursor at top of the document.

Cursor at bottom of the document.

Cursor at start point of current line.


Cursor at end point of current line.
Go to that line.
Cut the text.
Copy the text.
Paste te text.
Delete the current window.
Delete all the windows except the current
window
Split the current window into 2 (top and
bottom)
Split the current window into 2 (side by side)
Switch to another window .

C-x 1

C-x 2

C-x 3
C-x o

M-g: enter line number and enter

UNIT-1
PART-A
Q1.What are the advantages of Linux over windows?
Ans:
Multitasking
True multiuser system
Time sharing
Open source
Security
Low cost and performance
Q2.What is a shell and give an example?
Ans:
A shell is a program that act as an interface between the user and the linux allowing to enter the
commands to the operating system.
Eg:-bash,csh,ksh..
Q3.What is the use of CAT command?
Ans : Creates a new file
Syntax: cat > filename.txt
Displays the content of a file
Syntax: cat filename
Q4.What are info pages and how does they differ from man pages?
Ans:
Info pages contains reference materials for the commands library files, system calls in GNU . or
hypertext format
Although man pages are backbone for reference informations in linux for sometime, some
information ispresented in increasing in GNU info format.
Q5.Write a command to display shell name and version.
Ans:
/bin/sh -version
Q6.What is the need of #!/bin/bash in the first line of every bash shell script?

Ans:
The command #!/bin/bash indicates the name of the interpreter used to execute the script.
Q7.What are wild card characters and mention the uses of any two?
Ans:
Wild card characters: the characters which have some special meaning used in linux shell
commands.
Ex:- ?- matches any single character.
*-matches one or more characters.
Q8.Write a script to add two numbers
Ans:
echo enter the number
read a
echo $a
echo enter the second number
read b
echo $b
c=` expr $a + $b `
echo the sum of a and b is:
echo $c
Q9.What is meant by command substitution?
Ans : The output of one command is passed as an argument of another command. This process is called
command substitution
Ex:-lsA|cat|rev can be written in command substitution as rev$(cat$(lsA)).
Q10.What is an environment variable?
Ans:- environment variables are special variables those can be shared by different scripts.
Ex:- HOME,BASH,PWD etc.,
Q11.How to convert a normal variable into environmental variable?
Ans :- A user defined variable can also be set as an environmental variable by using export command.
Syntax:- export variable.
Q12.Write uses of any four commands using test?
Ans : test e filename : checks whether the file exists or not.
test x filename : checks whether the file is executable or not .
test d filename : checks whether it is directory or not.
test f filename : checks whether it is normal file.
Q13. Print the content of all the files in the directory in reverse order.
Ans : for i in *
do
if [ -f $i ]
then
cat <$i|rev
else
echo it is not a normal file
fi
done
Q14. What is the use of \t and \s in regular expression?
Ans:
\t- tab
\s- white space.
Q15. What is a sed command and what is its use?
Ans : sed is an stream editor.
It is a search engine used to edit a file.
Uses : 1. to replace a pattern
2.to search a pattern.

16)WRITE SOME OF THE USEFFUL TOOLS FOR SHELLSCRIPTS

TAC: copies from standard input to standard output. Reversing the order in which the lines appear.
TEE: copies the data from standard input to multiple sources. It can write the data to several files as to
standard output ,for instance.
TR: performs basic transformations on data. For instance, tr A-Z a-z will convert all capitals to
lowercase in its output.

17)WHAT IS THE DIFFERENCE BETWEEN ACCESSING PERMISSION TO A FILE AND EXECUTING


A FILE.
ACCESSING PERMISSION: chmod member + x
ex: chmod u+x
EXECUTING A FILE:sh filename
ex: sh abc.sh
18)WRITE USES OF REGULAR EXPRESSIONS.
Hi* mtaches
Hi, Hii, Hiiii...
linux is .*useful
linux isuseful(no whitespace i.e. matches even for zero characters)
linux is moreuseful.
linux is .+useful
linux is useful(does not allows for zero characters)
19)WHAT IS INFO COMMMAND?
INFO: Information is presented in GNU format.GNU info is a hypertext format that is used to
present information. It can be used in several viewers. They are standalone viewer(info),
a special mode
in EMACS, HTML ,x-based interfaces.
20)USE OF INFO PAGE NAVIGATION KEYS.
N-takes you to the next pagein sequence as displayed at the top of the screen.
P-takes you to the previous page in sequence as displayed at the top of the screen.
M-follows a link from menu, and asks you which entry to use.
spacebar-scroll forward by one page.
backspace-scroll backward by one page.
21) HOW TO REDIRECT FIRST 3 LINES OF LAST 5 FOR A GIVEN FILE.
Let the file be abc.sh

a)tail -n 5 abc.sh> temp.txt


head -n 3 temp.txt
b)using pipping
tail -n 5 abc.sh ! head -n 3
22)WRITE THE REDIRECTION WITH APPEND COMMANDS.
ls > abc.sh
who > abc.sh-create a newfile or delete the content and new data.
ls >> abc.sh
who >> abc.sh-append with existing content.
23)VARIOUS KEYS USED TO EDIT THE FILE IN VI EDITOR.
Esc+i : (insert mode) which is used to insert text into the file.
Esc+:+w : save file
Esc + : +wq :write and quit
24)WRITE THE USES OF SOME SPECIAL CHARCTERS.
0-filename
*-all arguments with blankspace as seperator
#-total number of arguments
+ :one or more times of preceding characters.
25)WHAT ARE THE STEPS INVOLVED IN USING ENVIRONMENTAL VARIABLE.
a)Assign the value to the variable
b)Export the variable as environmental variable using the command "export"
c)use environmental variable.
ex: $dept="IT"
$export dept
echo $$dept
26)WRITE THE SYNTAX FOR OUTPUT AND STANDARD ERROR REDIRECTION TO DIFFERENT
AND SAME FILE.
TO DIFFERENT FILE:
$ ls-l a*.txt > list 2 > error file (or)
$ls-l a*.txt 1 > list 2 > errorfile

If file is available result is redirected to file list or else the error message is redirected to
the error file
TO SAME FILE:
$ls -l a*.txt > &list res (or)
$ls -l a*.txt > list res 2 > &1
The output or standard errors are redirected to the file list res.
27)SYNTAX FOR TEST AND LOOP CONDITIONS.
a)if.....else....fi
if [ expression ]; then
statements
elif [ expresssion ]; then
statements
else
statements
fi
b)for while loop
while list; do
commands
done
c)FOR for loop
for name in list; do
commands
done
d)for function
function function name
{
statements
}
#function call
function name arg1 arg2 arg3
28)WHAT ARE THE DIFFERENT TYPES OF EXPRESSIONS.

a)string comparision
ex:[ s1=s2 ]
[ -ns1 ] (true if s1 has a length greater than 0,else false)
b)numeric comparision
ex: -eq -> equal to
-ne -> not equal to
c)file operators
ex: -s ->file exists and is not empty
-f ->file exists and is not a directory
d)logical operators
ex: && ->logically and
29)WHAT IS THE USE OF PIPPING?
PIPPPING is used to take output from one program and sent it directly as the input to another
program.
ex: $who ! wc -l
The output of who is passed as the input for the command wc -l. It will return number of users
connected with the system.
30)WHAT ARE THE DIFFERENT TYPES F KEY COMBINATIONS IN EMACS.
c - g -> cancel current command
c -x c -c ->exit emac
c -h ->help area
c -x c-f -> load a new file
c -x c-s ->save current file
c - x k -> close current file

PART-B
1.Discuss about Basic Linux Programming Concepts?
* The programming environment in linux is one hat follows one of the design philosophies of linux itself. If
many small components are given are given you can assemble in any way to solve the problem or task.
* Example for this is components. The components are pre processor,linker and assembler and a compiler. It
can be called manually to build a program else let the GCC front and automatically handles those details.
* Number of tools are commandline based,because it is easier to raise and automate command line tools.

* The C development environment on linux consists of the C development tools like compiler, linker, optional
project management utilities, editor or IDE(Emacs) and analysis tools (gdb).
* People who work in large groups require archiving use source cell control system(CVS).
* On linux, C library provides everything from basic string functions to functions that access the database of
users. The C library consists of both the library to be linked into four program and the set of header files.
2.Write about Linux Design?
* Multitasking: Multiple threads and processors can be created at once. It cannot be assumed that there is
only instance of program running: both the same users and other users may be running other copies of it.
Synchronisation of the access must be careful.
* Multiuser System: There are security measures involved to isolate one user's file from another. And users
program will not be able to modify or replace any file on the system as they can run on some other platforms
unless they are running as a superuser (root).
* Time sharing: It means that there can be several users logged into the system at once or a single user may
be logged in more than once. People use technologies like Telnet or Xtolog to that they may be executed by
several users simultaneously.
3.Discuss about the concept of Man Pages?
* Man pages are the main stay of reference information. a primarily reference material and one man page
exists for virtually every shell command, system call, library function, configuration file and daemon on the
system.
* The entries in man pages presuppose knowledge, about the topic and contains some examples
Man pages are divided into 8 sections
Section 1: Shell commands and user level programs
Section 2: System calls.
Section 3: C and C++, library calls and micros.
Section 4: Special files and decices like kernel, kernel
modules/dev entries/proc entries.
Section 5: Format of various files on the system, mostly
configuration files.
Section 6: Games (but mostly covered in section 1.)
Section 7: Languages such as SQL or mini languages.
Section 8: Daemon or other system admin commands.
* To lookup a manpage,
Command is " man topic "
where topic is the name command or file or program orfunction or macro.
Example: man ls - There is only one entry in section 1.

Navigation: Man invokes more or less to display the page.


Spacebar Advance the page
Enter

Advance a line

Go back

To search

To quit

* Kill: Kill entry is a command on section 1 and system call in


section 2.
Command:
$ man section topic
* Typeset hardcopy of any man page can be obtained if there is a configured printable in linux.
Command:
$ man -t 2 kill lpr
Here -t instructs the system to generate post script output which is output which is then piped to printed
spooler.
* To perform keyword search
Command:
$ man -k syslog
syslog is present in sections 2, 3, 5, 8
* The command $ man man will display into about man pages.
4.Discuss about Redirection and its types?
* One of the most powerful features of linuxshell.
* Redirection enables to take that which would normally be displayed on the terminal and save it into a file'
* By default each program has three standard file handlers. Standard i/p, o/p and standard error.
* Standard i/p is used for reaching data and reads data from terminals keyboard by default.
* Standard o/p is used for displaying normal data and connected to terminal screen by default.
* Standard error is used for displaying error messages and connected to terminal screen by default.
Name
Std i/p

Shorthan
d
stdin

Std o/p

stdout

Numbe
r
0
1

Purpose
Reading i/p
for program
Dislpaying normal o/p from a program

Default
Connections
Terminal is
keyboard
Terminal
display

is

Std
error

stderr

Displaying error msgs or warnings of unusual


situation

Terminal
display

is

Output Redirection:
* The messages that normally that go to the screen are placed in the file.
* Output redirection symbol >
* It requests that the items that normally goes to std o/p is sent to the specified file.
* Bash provides a special redirection operator that opens files in append mode. That is if there is data in file,
the new data is added to end of file.
Append operator >>
Redirection of output and std error to different files:
eg: $ ls - l a*.txt 1> list 2>error file
Here channel 1 - standard o/p redirection
channel 2 - standard error redirection
Here if the file is a variable result redirected to the file list or else the error msg is redirected to the error
file.
Redirection of std o/p and std error to same file:
Symbol for redirection >&
eg: $ ls - l a*.txt >& list Res
(OR)
$ ls - l a*.txt > list Res 2 >& 1
The o/p or standard errors are redirected to the file 'list Res'
Input Redirection:
Input redirection enables to substitute the contents of a file, for what would normally be typed on the
keyboard.
That is it redirects the input for a command from the text file.
Eg: $ rev <abc. text
Piping:
* Piping enables to chain commands together sending the output from one command into the input of the
next.
* All the commands run simultaneously processing the data is sent directly from one process to next.
* Vertical bar char is pipe
Eg: $ who wc - l

The output of who is passed as the i/p for the command wc - l. It will return number of users connected
with system.
Variables:
* Data can be stored in files but variables are necessary in order to accomplish more complicated task.
* Assigning values to variables is very simple. It is done by using ' = ' operator.
Eg: $ Name = listing
* To display the variable, the command is
$ echo $ variable
* To remove a variable, ' unset ' command is used. This command will delete variables and memory holding
its contents.
* When a variables is used inside the double quotes, the variable is inserted verbatin, that is its contents are
not examined further by the shell. When it is outside the quotes, the shell is free to examine its contents.
Eg: $ MYVAR = /dev/hda*
$ echo " $ MYVAR "
/dev/hda*
$ echo $ MYVAR
o/p /dev/hda/devhda/......
Here without quotes ' * ' ( wildcard ) is expanded.
5.Discuss briefly about Environmental variable?
There is a special type of variable known as environmental variable. These variables are special in two ways.
1. They can be passed to your script by other programs.
2. Any programs that are invoked from the script inherit the environmental variable.
Three steps for implementing Environmental Variables:
1. Assign value to variable.
2. Export the variable as Environmental variable using
command export.
3. USe Environmental variable.
Eg: $ name = " SASTRA "
$ export name
$ echo $ name
* To list all the environmental variable
$ set

* To remove/release environmental variable


$ unset variable name
Eg: unset name (enter)
6.Discuss about Functions and write its syntax with an example?
Functions within the shell scripts are used to minimise the need to retype the code multiple times.

Syntax:
function functionname

Function block

{
statements
}
For function call
functionname arg1 arg2 arg3
Eg:
function add
{
res = 'expr $1 + $2'
echo $res
}
add 5 10 function call.

7.Discuss about Conditionals and Loops?


A conditional is a language construct that enables program to do one thing if given expression is true
and a different thing if the expression is false.
Expressions:
An expression can be a string comparison, numeric comparison, file operators and logical operators and is
represented by [ expression ].
String comparisons:
1. ' = ' compares equality of two strings
Eg: [ s1 = s2 ]
2. ' != ' compares unequality of two strings

Eg: [ s1 != s2 ]
3. ' -n ' evaluate if string length is greater than zero.
Eg: [ -n s1 ]
4. ' -z ' evaluate if string length is equal to zero
Eg: [-z s1 ]
Numeric Comparisons:
-eq equal to
-ne not equal to
-lt less than
-gt greater than
-le less than or equal to
-ge greater than or equal to
File Operations:
-x execute file
-w write file
-r read file
-s file exists and is not empty
-f file exists and is not directory
-d directory exists
-e check if file name exists
Logical Operators:
&& logically AND two logical expressions
|| logically OR two logical expressions
8.Discuss about Conditional Statements with few examples?
1. if...else...fi
Here checks the condition and enters the block to execute.
Syntax:
if [ expression ]; then
statements
elif [ expression ]; then

statements
else
statements
fi (end if)
Eg
echo "Enter a number 1 < x < 10"

1:

read num
if [ "$ num" -gt 1 ] && [ "$num" -lt 10 ];
then
echo " $num * $num = $(( $num * $num ))"
else
echo " wrong insertion "
fi
Eg 2:
echo " Enter your username "
read x
echo " Enter password "
read y
if [ $x = " hpstudents " ] && [ $y = " SASTRA " ];
then
echo " Access granted "
else
echo " Access denied "
fi
Eg 3:
echo
read filename
if [ " -s " $ filename ];
then
if[ -x " $ filename" ];
then

"

Enter

filename

"

echo " executable file "


elif [ -w " $ filename " ];
then
echo " writable file "
elif [ -r " $ filename " ];
then
echo " readable file "
else
echo " File exists and not directory "
fi
else
echo " It is directory "
fi
If with text:
if test -x $ filename ; then
echo " $ filename is executable "
elif test -r $ filename ; then
echo " $ filename is readable "
Case Statements:
Used to execute statements based on specific values. Often used in place of an if statement if there are a large
number of conditions.
Value used can be an expression.
Each set of statements must be ended by a pair of semicolons.
* ] Used to accept any value not matched with list of values.
Syntax:
Case $var in
val 1)
statements;
val 2)
statements;
*)

statements;
esac ( to end case )
Eg:
echo " Enter the values of a and b "
read a
read b
echo " 1. add 2. subtract 3. mutliplication
4. quotient 5. remainder "
readch
case $ ch in
1) echo " Sum is $ (( $a + $b )) " ;;
2) echo " Difference is $ (( $a - $b )) " ;;
3) echo " Product is $ (( $a * $ b )) " ;;
4) if [ $b -eq 0 ] ; then
echo " Not possible "
else
echo " Quotient is $ (( $a / $b )) ;;
fi
5) echo " Remainder is $ (( $a % $b )) ;;
*) echo " Unrecognised value " ;;
Loops:
Iteration statements:
while:
It is a looping structure which is used to execute a set of commands while a specified condition is true.
Syntax:
while list ; do
statements
done
Eg1 :
i=0

while [ $i -le 10 ] ;
do
echo $i
i = $ (( $i + 1 ))
done
Eg2 :
echo -n " Enter num "
read x
sum = 0
i=1
while [ $i -le $x ] ;
do
echo " Sum = $ (( $sum + $i ))
i = $ (( $i + 1 ))
done
echo " Sum of first $x no s is : $ sum "
For:
The for statement is used when we are looping through a range of variables.
Syntax:
forvar in list;
do
statements
done
Eg1 :
n=5
for i in 1 2 3 4 5 6 7 8 9 10 ;
do
echo " $n * $i = $ (( $ i * $ n ))
done
Continue Statements :

Continue command causes a jump to the next iteration of loop , skipping all the remaining commands in
the particular loop cycle.
Eg1 :
LIMIT 1 = 19
echo " printing numbers 1 to 20 ( but not 3 and 11 ) "
a=0
while [ $a -le $LIMIT ] ; do
a = $ (( $a + 1 ))
if [ $a -eq 3 ] || [ " $ a -eq 11 " ]
then
continue
fi
echo -n " $a "
done
Until statements :
*) Until structure similar to while structure.
*) The until structure loops until the condition is true.
*) Until the condition is true do this
until ( expression )
Syntax :
until ( expression )
do
statements
done
Eg :
echo " Enter a num "
read x
echo countdown
until [ " $x " -ge 0 ]; do
echo $x
x = $ (( $ x - 1 ))

sleep 1
done
echo " Go! "
9.Describe about Shell Utilities ?
There are a number of shells utilises that can be used in script while programming . Some of these are
implemented as shell buittins i.e., shell handles the command rather than a separate program. Many of them
read from standard i/p and write to standard o/p. This means that they are ideal for being combined with
others in a pipeline.
Eg
cat somefile.txt sort uniq tac
This will read data from some file. Sort it, remove the duplicates, and then invert the order of 3 lines.
Command
Awk
Bash
Cat[file...]

Exec
command
[arguements...]
Find
Grep / egrep
Gunzip
Gzip

perl
rev
sed

tac
Tee
Tr
Sort
uniq

Purpose
This is an interpreter for the awkprogramming language.
Starts up another shell process beneath the current one.
Reads from each specified file in order, displaying its entire contents to standard
output.
The effect of this is to concatenate the files together, hence the name. If no names are
specified, cat copies from standard input to standard output.
Executes the specified program, with the given optional arguments. This program
replaces the current shell. That is, the current shell ceases to exist once the program
begins. When the program exits, you will probably be logged off or your xterm closed
Selects files based on a search through directories for files with matching name,
modification dates, permissions, or other attributes. The manpage for find contains an
exhaustive description of its syntax
Search inside of files for specific text or patterns. The egrep tool uses regular
expressions for searches, and on Linux, grep can use regular expressions as well.
Sends uncompressed data to standard output when compressed data is piped to
gunzip
Reads data on standard input, and writes a compressed version to standard output.
This command can be used in a pipe. Normally, after the data is compressed, the
pipeline ends; the data will be saved to a file. This program can also work on separate
files.
Invokes the interpreter for the Perl programming language
Copies from standard input to standard output, reversing the order of the characters
in each line of the file.
Reads from standard input, makes some modifications to the data, and writes the
result to standard output; that is its a stream editor. Today, the most frequent use of
sed is its pattern replacement operator, s///.
Copies from standard input to standard output, reversing the order in which the lines
appear (but not the order of characters in those lines).
Reads from standard input, and copies the data to multiple sources. It can write the
data to several files as well as to standard output, for instance
Performs basic transformations on data. For instance, the command tr A-Z a-z will
convert all capital letters to lowercase in its input. This command reads from
standard input, makes the modifications, and writes the result to standard output.
Reads from standard input, sorts the lines in the file, and writes the ordered data to
standard output.
Removes duplicate lines from input. You usually have to send the input through sort

before you can send it through uniq. The output from uniq is the same as the input,
with duplicate lines removed.
10.Write about Regular Expressions?
* A regular expression is a pattern of characters used for describing a set of strings.
* Regular expressions provide an alternative to writing search
algorithm. With regular expressions we
define a pattern that we are looking for and the regular expression engine do the searching for us.
* Regular expressions are not tried to any particular language. Regular expressions support in grep, sed,
selleal libraries for C, and several of the languages utilities as well.
Pattern :
A pattern is the first step to writing a useful regular expression. It is used to figure out what sort of pattern
are present in a data.
A pattern consists of
* Upper and lower case
* Digits
* Space , underscore etc and
Metacharacters
* Patterns that match a single character
All regular letters that match themselves.
abzTQ 019
' . ' ( a single dot ) matches any single character except new line.
* In awk , dot can match new line also like ? in filename generation.
A set of characters that matches any single character from the set.
1. [ aeiou ]
2. [a-z 0-9 ]
3. [A-Z a-z ]
4. [a-m ]
*Metacharacters
This matches 0 or more occurences of the preceding char
[.....] Matches any one of the chars enclosed between the brackets.
' - ' Dash indicates a range when inside square brackets.
[ ^ ] Negates whats inside brackets.

\ - backslash - escapechar-.
\. Means match a dot.
\\ Means match slash.
Position indicators :
^ anchor to beginning of line.
$ anchor to end of line.
' + ' One or more times preceding char.
Syntax
\

\0xx

Description
Escape operator; the next character (if special)
has its literal meaning. Some languages may
ascribe special meanings to sequences with
normal characters, such as \n.
Matches the octal character indicated by the xx
digits.

\a

Matches the ASCII bell character. This is the


same as \x07 and\007.

\A

Matches the beginning of the string. This is a


Perlism; it acts exactly like the caret character
(^)
except it does not match multiple times when the
m option is used.
\AHello matches only a string whose
first five letters are Hello.
The opposite of \b, matches any location that is
not a word boundary.
Matches any digit character. The definition of
this varies between implementation and locale,
but you
can generally consider it to be the same as [0-9].
The opposite of \d, matches any character that is
not a digit. and even Report___.txt.
Matches the ASCII form-feed character.

\b
\B
\d

\D
\f
\n

\r
\s

Matches the ASCII newline character. With


some implementations, this may match the
carriage
return
character
also.
Some
implementations strip off the final newline
before passing the string to
the regular expression parser, so if you are
looking for the end of the line, you may want to
use $ instead.
Matches the ASCII carriage return character.
Matches any white space character. The exact
definition of this can vary potentially between

Example
Foo.*\.txt matches any string beginning with
Foo and ending with .txt.
Bell\007Beep matches a string that
begins with Bell, and then has the ASCII bell
character, and ends with Beep.
Bell\aBeep matches a string that begins with
Bell, and then has the ASCII bell character,
and ends with Beep.
\AHello matches only a string whose
first five letters are Hello.

1234\b.+9 matches 1234 2359 and 1234 a9


but not 1234a9.
1234\B.+9 matches 1234689 and
1234asdf9 but not 1234 589.
Report\d+ matches Report12,
Report1351134, and Report0, but not
ReportA.
Report\D+ matches ReportA,
ReportForBob,
Form\fFeed matches a string containing the
words Form and Feed, separated only by the
ASCII form-feed character.
ine1\nLine2 matches a Lstring
containing two lines, with the first
ending with Line1 and the second
beginning with Line2.

Word1\rWord2 matches a string


containing Word1 and Word2, separated
only by the carriage return character.
Foo\s+Bar matches a string ontaining
Foo and Bar, cseparated by at least one

\S

locales, but generally include spaces, tabs,


carriage
returns, and linefeeds.
The opposite of \s, matches any character that is
not a white space character.

\t

Matches the ASCII horizontal tab character.

\w

Matches a word character. This will vary


between locales, as the alphabet in some areas
includes
characters not present in others. In English, this
is generally the same as
[0-9a-zA-Z_].
Matches the character specified by the two-digit
hexadecimal number yy.
The opposite of \w, matches any character that
would not be matched by \w.

\xyy
\W
\Z
.

[...] character
class

[[:alnum:]]

[[:alpha:]]

This is a Perl-ism. This acts like $, but doesnt


match multiple times when the m option is in
effect.
Matches any single character Depending on the
implementa- tion and options given to the
regular expression engine, this may or may not
match a newline character.
Denotes a character class. This usage gives a
listing of characters, any of which may be
matched once. Ranges may also be specified.
Negation may
be specified by using a leading ^ after the
opening bracket.
Matches alphabetic and numeric characters; the
same as [[:alpha:][:digit:]]

Matches alphabetic characters. The definition of


this may vary between locales, but in English, it

white space character.


Foo\S+Bar matches a string containing Foo
and Bar, with at least one non-white space
character between them. For instance,
Foo1234Bar,Foo_Bar,Fooqwerty Bar and
FooBazBar.
Tab\tHere matches text with an
embedded horizontal tab character.
The pattern \w+ matches any word
without embedded white space.
Examples include Linux4You,
RegexpsAreFun, and so on.
The pattern \x07 matches the ASCII bell
character.
The pattern \W+ matches any string
without word characters in it. Examples
include !<>, \~`, and ;.
The pattern .*end\Z matches such strings as
end, This Is The end, Im at the strings end,
and so on.
Hello.txt matches Hello4txt, Helloqtxt,
Hello!txt, and even Hello.txt.
Letter199[14-79] matches only
Letter1991, Letter1994, Letter1995,
Letter1996, Letter1997, and Letter1999.
Letter199[^14-79] matches many items, such
as Letter199Q, Letter1992,
Letter1991, and many more.
The pattern Word1[[:alnum:]]+Word2
matches patterns such as
Word1HelloWord2,
Word1123456789Word2, and any others
with at least one alphanumeric character
between Word1 and Word2.

The pattern Word1[[:alpha:]]Word2


matches patterns such as Word1HelloWord2

generally means [A-Za-z].

[[:blank:]]

Matches horizontal white space characters.


Currently, this matches only space and tab.

[[:cntrl:]]

Matches the ASCII control characters, which


are generally characters 1 through 31 in ASCII.

[[:digit:]]

Matches any numeric character. This is the same


as writing [0-9].
Matches non-white space characters that are
printable. This includes, for instance, alphabetic
characters, numbers, and so on.
Matches lower-case alphabetic characters. In
English locales, this is the same as [a-z].

[[:graph:]]
[[:lower:]]
[[:print:]]
[[:punct:]]

[[:space:]]

Matches printable characters. This is the


opposite of[[:cntrl:]]
Matches punctuation characters. This can vary
significantly between locale, but for English
locations, consider it to be essentially any
nonalphanumeric keys in the main area of your
keyboard.
Matches white space characters. These might
include space, tab, carriage return, linefeed,
form feed, vertical tab, and so on.

[[:upper:]]

Matches uppercase letters. The precise listing of


the letters that match can vary between locale.

[[:xdigit:]]

Matches characters that are valid hexadecimal


digits.

{x}

Matches the preceding character or operator


exactly x times.
Matches the preceding character or operator at
least x times.
Matches the preceding character or operator no
less than x times and no more than y times.
Denotes alternation in a pattern, used to specify
multiple options for matches at a particular
point. Unless used inside the grouping operator,
( ... ), the entire regular expression is split into
pieces, any of which will be considered a
successful match.
Indicates that the preceding operator should
match as few times as possible while still

{x,}
{x,y}
|

and Word1GoodbyeWord2, and any others


with at least one alphabetic character
between the first and second words.
Numeric characters do not match this
pattern.
The pattern Lots[[:blank:
]]+Of[[:blank:]] Spaces matches patterns
such as Lots Of Spaces, Lots Of Spaces, and
Lots Of Spaces.
The pattern Strange[[:cntrl:]]Characters
matches two words separated by one
control character.
Hi [[:digit:]]+ matches such strings as Hi
123456789, Hi 12, and Hi 99.
The pattern To:[[:graph]] matches a
string such as To:q, To:5, and so on.
The pattern [[:lower:]] matches such
strings as linuxprogrammingisfun,
regularexpressionsareuseful, and so on.
[[:print:]]+ matches almost any string that
contains plain text characters.
The pattern [[:punct:]] matches such
characters as %, (, and $.

Word1[[:space:]]+ Word2 matches two


words separated by at least one white space
character. They could perhaps be on
different lines or even different pages,
depending on your language and options.
The pattern [[:upper:]]+ matches any
string consisting solely of uppercase
characters. Examples include WOW,
HELLO, LINUX, and GNU.
The pattern [[:xdigit:]] will match strings
containing solely hexadecimal
characters. Examples of these can
include 01234ABCD, F00F, AA55, and
FFEF.
Q{5} matches only the string QQQQQ.
Q{5,} matches strings such as QQQQQ,
QQQQQQQ, and QQQQQQQQQQ.
Q{3,5} matches only the strings QQQ,
QQQQ, and QQQQQ.
Report.|Memo199. matches such strings as
ReportA,
Memo1999,
Report2,
and
Memo199a.

The pattern .+?(Q+) ensures that the


trailing Q characters in the string are

allowing the regular expression to find a match.


This is valid in Perl only.

Matches the end of the current line. This does


not correspond directly to any particular
character; it is simply used to match the end of
the line. Language
options and imple- mentation details may
modify the notion of line.
Matches the beginning of the current line. This
does not directly correspond to any particular
character; it is simply used to match the
beginning of a line. Language options and
implementation
details may modify the notion of line.
Modifies the behavior of the immediate
preceding character or operator to match 0 or
more times.

returned. With this question-mark


operator, a string such as LinuxQQQQ
returns the QQQQ string. Without it, the
same string returns only a single Q because
the .+ before matches the remaining ones.
Linux.$ matches only the strings that end
with the word Linux and then one other
character.

^Hello matches only those lines whose first


five characters spell Hello.

Document.*html matches any string


beginning with Document and ending

11.Explain about Grep and Egrep with its syntax?


grep : globally regular expression print.
working:
* grep looks inside files and returns any line that contains the string or expression.
* Print lines matching a pattern to standard o/p.
* The metacharacters (?,+,(,) etc) donot have special meaning unless escaped with \.
Syntax:
Grep patterns filename.
Eg:grep permission file1 file2
file1:
file2:
ifgrep cannot find a line with in any of the specified files that contain the requested pattern no o\p is
produced.
Grep exit status:
$? is set to 0 if grep finds something.
$? is set to 1if grep finds nothing.
$? is set to 2if one of the i/p file not found.
Grep options:

grep [options]pattern [file---].


-i : ignore case.
-n : list line number along with matching line.
-v : invert match.
-w : matches the whole word.
-c : print the number of lines where the pattern found.
Egrep:
* The egrep tool is fundamentally simple if a pattern or data is given then it displays all the lines that the
pattern is capable of matching.
*When we invoke egrep, it expects atleast on one
piping and
redirectional if no file name is given.
egrep extended or enhanced grep.
(grep-E)
Syntax:
egrep regular file1 file2....
* The metacharacters ?,+,{,|,(,and) have their special
meanings.
egrep '3+'datafile.
egrep '2\.?[0-9]'datafile.
egrep ' sh \ u ' datafile.
* It has some options as grep.
12.Explain about Sed( Stream Editor )?
* Anon interactive text editorthat is called from unix
command.
* They have similar syntax to grep and egrep.
* Input text one time at a time flows through the program. It
is modified and is directed to standard output.
* Allow the use to specif instructions in script.
* Allows the editing of text similar to vi editor.
* Hence modifications like insertion, deletion etc. can be
carried out.

parameter, the pattern to look for. It requires

Syntax:
sed [ option ] ' instruction' file (s)
Options:
-n only prints matches
-f script file runs commands in script file
-e allows multiple instructions on a single line
Sed Commands or Instructions:
a append
d delete lines
c change lines
i insert
p print
s substitute
Eg: echo " hai hw are you " sed ' s / hw / how
Output :hai how are you.
Here hw is substituted by how.
awk:
* Sed and awk systems add some unique options that act
like character class.
* Extended meta characters and alternation words in awk
* Sed and awk do not use exit status to indicate the success or failure of the locating pattern. The report
failure only if there is a syntax error in a command.
13.Discuss about Emacs?
Emacs is an extensible, customisable, self documenting and real time display editor.
Emacs key notations:
The emacs key sequence notations is used to specify keyboard combinations that are used to invoke
commands.
* Keys that should be pressed simultaneously separated by
' dashes '.
Keys pressed in series .space
C is used for control keys

M is used for meta keys ( alt, windows, esc)


RET used for enter key.
C-X used for control and X.
Key Combinations:
c-g cancel current command.
c-x c-c exit emac.
c-h help area.
c-x c-f load a new file.
c-x c-s save current file.
c-x k close current bash.
c-x s save all open files.
Navigations:
M - < or c - home or esc +shift +command cursor at top of the document.
M - > or c - end cursor at the bottom of the document.
c - a cursor at start point of current line.
c - e cursor at end point of current line.
Go to line:
M - g enter the line number and RET.
Searching and Replacing:
c - s find word forward
c - r find word in reverse.
M - % replace with prompt.
M - x ' replace string ' replace without prompting
c - g cancel the search.
Cut and Paste:
c - w cut the text.
M - w copy the text.
c - y paste the text.
Buffers:
Here editing takes place, but there may also contain program output.

c - x b select another buffer.


c - x c - b list all buffers
c - x k kill current buffer

Multiple Windows:
c - x 0 delete the current window
c - x 1 delete all other windows
c - x 2 split window horizontal
c - x 3 split window vertical
c - x o switch to another window
Cursor Movements:
Important because they make movement test.
c - d delete char
c - f forward one char
c - b back one char
c - n next line
c - p previous line
c - a beginning of line
c - e end of line
c - o new line ( enter )
M - d delete word
M - f forward one word
M - b back one word
M - } forward one paragraph
M - { back one paragraph.

UNIT-2
PART-A
1.what are seekable and non seekable files?give examples.
2.what system call is used to create device and named pipes in the file system.give its syntax?

3.what system call is used to change the access mode for an open file?
4.what are the types of files?
5.what are the macros to check file types?
6.what are the header files used in file handling?
7.define inode?
8.How to create hard link ,soft link and give its syntax?
9.what are the types of file locking and give its syntax?
10.write the types ofduplicating file descriptors and give its syntax?
11.Give the syntax of file non-blocking?
12.what are the methods used for querying and changing inode information?
13.what is the use of truncate and write its syntax?
14.how to process UMASK?
15.what are the different modes of opening a file?
16.what is dangling link?
17.write about sticky bit?
18.how to rename file?
19.write the syntax of mmap()[MEMORY MAPPING]?
20.write about input and output multiplexing?

PART-B
1

What are the different types of File access modes explain them with their syntax?
[pg no:145]

What are the types of files and explain briefly about them?
[pg no:148]

Discuss briefly about Pipes?


[pg no:183]

Write briefly about Querying and changing inode information?


[pg no:162]

Discuss about Memory Mapping?


[pg no:215]

6. Discuss briefly about File Locking?


[pg no:223]
7. What are the uses of Advance File Handling and explain them?
[pg no:205]
8 . Write briefly about CHMOD and its octal representation of access rights?
[pg no:145]
9. What Is UMASK and explain with a suitable example?
[pg no:149]
10.Discuss about Manipulating Directory Entries with their syntax and example?
[pg no:173]

UNIT-3
PART-A
1 why do we use signal handlers? (Pg 242)
2 Name the two special signal handlers which restores the system default behavior when the signal is
received. (pg 243)
3 Which method is used to send a signal to yourself. (pg 255)
4 Name the signals generated by exit command. (pg 256)
5 Which method is preferred more? signal() or sigaction()? Justify. (pg 261)
6 Why signal blocking is needed? (Pg 246) Linux app development book
7 List 3 things that a process can do when it is signaled. (pg 203)
8 What are unreliable signals? (pg 207)
9 What are two types of system calls? (pg 209)
10 Mention the macros used in blocking and unblocking. (Pg 213)
11 What are the two methods passed to the method pause()? (Pg 214)
12 Give any two reentrant functions. (pg 222)
13 What is mean by datagram protocol? (pg 384)
14 What is mean by stream protocol? (pg 384)
15 Mention four socket errors. (pg 390)
16 What is mean by pending connection? (pg 390)
17 Mention the parameters used to specify the stream connection protocols. (pg 388)

18 Write any four protocols and address families with descriptions. (pg 385)
19 Sketch the establishing socket connection. (pg 391)
20 Mention some IP protocols with descriptions. (pg 389)
PART-B
1. How to block a signal ?

CHAPTER- 13

PAGE: 246-248

2. What are the ways to send the signals?

CHAPTER-13

PAGE: 255-256

3. What are pending signals and explain about it?

CHAPTER -13

PAGE: 248-250

4.What is meant by input and output streaming in signals? CHAPTER-14 PAGE:263-266.


5.What is client side connection?

CHAPTER-18

PAGE:356-358

BOOK:LINUX APPLICATION DEVELOPMENT


6.What is socket error and how to handle it?

CHAPTER-16

PAGE:355-356.

7.What is server side connection? Discuss in detail.

CHAPTER-18

PAGE:358-362.

8.How to manipulate process using sigmask?

CHAPTER-13

PAGE:244-245.

9.What is catching signal?Explain in detail.

CHAPTER-13

PAGE:240-243.

10.Discuss in detail about networking machines ?

CHAPTER-16

PAGE:340-346.

11.What are the available signals in linux programming? CHAPTER-13

PAGE:247-251.

UNIT-4
PART A
1.What are Regular expressions ?
Ans: pg 519.
2.What is Regmatch_t ?
Ans: pg 521.
3.What is GREP ?

Ans: pg 524.
4.What is S-lang library ?
Ans: pg 529.
5.What are the two categories in which S-lang terminal handling abilities
Fall ?
Ans: pg 529 [ 3 paragraph].
6.What is Input handling ?
Ans: pg 530.
7.What are the two sets of S-lang terminal output functions ?
Ans: pg 533.
8.What are the two character sets that supports modern terminal ?
Ans: pg 535.
9.What are the S-lang shortcut functions ?
Ans: pg 538.
10.Mention the application of S-lang using colors ?
Ans: pg 540.
11.List the S-lang colors .
Ans: pg 540.
12.What are the different APIs that provides QDBM ?
Ans: pg 543.
13.What are the two ways to Read records from the Database ?
Ans: pg 547.
14.What are the two Operations that modify the QDBM databases ?
Ans: pg 549.
15.What are the types of Database ?
Ans: pg 430.
16.What is a major shortcoming of DB files ?

Ans: pg 433.
17.Explain the following flags parameters of a Record ?
1. R_FIRST
2. R_CURSOR .
Ans: pg 434.
18.Why does R_LAST and R_PREV are not available for hashed DB ?
Ans: pg 435.
19.What are the two operations that modifies DB ?
Ans: pg 435.
20.What are the two ways to read a records from the DB ?
Ans: pg 434.

PART B
1
2
a
b
3
4
5
6
7
8

Explain in detail the concepts of Linux console capabilities ?(pg-391)


Dicuss in detail about
Globbing Arbitrary strings
Regular Expressions (pg-408)
Explain in detail about input handling with an example ?(pg-416)
Explain in detail about output handling with an example ?(pg-419)
Explain basic operations of database library ?(pg-431)
Write a C program to perform the client side operations under linux networks?
Write a C program for IPC using shared memory?
Write a C program to read a character at a time from terminal and print each character on its own
line is fairly straight forward ?(pg-416)
9 Write a C program to implement the concept of PIPE?
10 Discuss the following in detail:
a Reading records
b Modifying the database

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