Module 2 - USP
Module 2 - USP
Prepared By:-
Mrs Saranya Babu,
Asst. Professor, Dept of CS&E
UNIX PROGRAMMING 18CS56- Module 2 MODULE-2
Showing hidden files (-a) : The hidden files residing in the home directory or any other directory are
normally don’t show up in the listing. –a option lists all hidden files as well:
Listing directory contents : If you specify directory name as an argument to ls command then it will
list the contents of the directory. We can also specify multiple directory names with ls command.
Consider the following example where CSA and isb are two directories
$ ls CSA isb
CSA:
marks list student list
isb:
absent present
Recursive listing (-R) : The –R option lists all files and subdirectories in a directory tree. It traverse
the directory tree until there are no subdirectories or files left.
The list shows the filenames in three sections – the one under the home directory and those under the
subdirectories helpdir and progs.
./helpdir indicates that helpdir is a subdirectory under . (current directory)
For example,
$ ls -l total 72
-rw-r--r-- 1 kumar metal 19514 may 10 13:45 chap01
-rw-r--r-- 2 kumar metal 19555 may 10 15:45 chap02
drwxr-xr-x 2 kumar metal 512 may 09 12:55 helpdir
drwxr-xr-x 3 kumar metal 512 may 09 11:05 progs
It lists seven attributes of all files in the current directory and they are:
• File type and Permissions: First column indicates the file type and its permissions that
are associated with each file. The first – indicates that file is ordinary file and a “d”
indicates its a directory.
• Links: Second column indicates number of links associated with file. Links indicate the
number of file names maintained by the system. This does not mean that there are so
many copies of the file.
• Ownership: File is created by the owner. The one who creates the file is the owner of
that file. In the above example third column shows kumar as the owner of the files • Group
ownership: Fourth column indicates the group owner of the file. Every user is attached to
a group owner. Every member of that group can access the file depending on the
permission assigned.
• File size: File size in bytes is displayed in fifth column. It is the number of character in
the file rather than the actual size occupied on disk.
• Last Modification date and time: Last modification time is the next field(6 th,7th and 8th
column). If you change only the permissions or ownership of the file, the modification
time remains unchanged. If at least one character is added or removed from the file
then this field will be updated.
• File name:In the last field, it displays the file names arranged in ASCII collating
sequence.
For example,
• Directories are easily identified in the listing by the first character of the first column, which
here shows a d.
• The significance of the attributes of a directory differs a good deal from an ordinary file. • To
see the attributes of a directory rather than the files contained in it, use ls –ld with the directory
name. Note that simply using ls –d will not list all subdirectories in the current directory. Strange
though it may seem, ls has no option to list only directories.
FILE PERMISSIONS
UNIX follows a three-tiered file protection system that determines a file‘s access rights. It is
displayed in the following format: Filetype owner (rwx) groupowner (rwx) others (rwx)
Consider an example
$ls -l
-rwxr-xr-- 1 kumar metal 19514 may 10 13:45 chap01
⚫ Here first column represents file permission. UNIX follows a three-tiered file protection
system that determines a file‘s access rights. The initial – represents it as an ordinary file.
r w x r-x r--
• The first group has all three permissions. The file is readable, writable and executable by the
owner of the file.
• The second group has a hyphen in the middle slot, which indicates the absence of write
permission by the group owner of the file.
• The third group has the write and execute bits absent. This set of permissions is applicable to
others.
• You can set different permissions for the three categories of users – owner, group and others.
It‘s important that you understand them because a little learning here can be a dangerous
thing. Faulty file permission is a sure recipe for disaster.
Relative Permissions
chmod only changes the permissions specified in the command line and leaves the other permissions
unchanged.
Its syntax is:
chmod category operation permission filename(s)
chmod takes an expression as its argument which contains:
• user category (user, group, others)
• Category :
o u – user
o g – group
o o – others
o a - all (ugo)
• operations :
o + assign
o - remove
o = absolute
• permissions:
o r – read
o w – write
o x - execute
Absolute Permissions
• Here, we don’t need to know the current file permissions.
• All nine permissions can be set explicitly. A string of three octal digits is used as an expression.
• The permission can be represented by one octal digit for each category. For each category, we
add octal digits.
• If we represent the permissions of each category by one octal digit, this is how the permission
can be represented:
Read permission – 4 (octal 100)
Write permission – 2 (octal 010)
Execute permission – 1 (octal 001)
• We have three categories and three permissions for each category, so three octal digits
can describe a file‘s permissions completely. The most significant digit represents user
and the least one represents others. chmod can use this three-digit string as the
expression.
• Using relative permission, we have,
• For example octal value of 644 ( 110 100 100) means:
o User (6) can read and write
o Group (4) can read only
o Others (4) can read only
• Example 1:- to give all permission for user and only read permission for group and others
chmod 744 start is same as chmod u+x start (relative)
$ls –l start
-rwxr--r-- 1 kumar metal 1906 sep 23:38 start
• Example 2: to assign read,write execute for user and execute permission for group and others,
chmod 711 start
$ls –l start
-rwx--x--x 1 kumar metal 1906 sep 23:38 start
• Example 3: to assign read write permission for all
$ chmod 666 start;
$ls –l start
-rw-rw-rw- 1 kumar metal 1906 sep 23:38 start
• Example 4: to assign all permission to the owner, read and write to group and only execute for
others
$ chmod 761 start
Security implications
• Consider the default permission of the file start as
-rw-r--r-- 1 kumar metal 1906 sep 23:38 start
These permissions are safe as only user can edit the file.
• Consider the case where we remove all permissions as :-
chmod u-rw,go-r start or
chmod 000 start
now , $ ls –l start
---------- 1 kumar metal 1906 sep 23:38 start
This permission makes the file useless, only user can delete this file
Once ownership of the file has been given away to sharma, the user file permissions that previously
applied to Kumar now apply to sharma. Thus, Kumar can no longer edit note since there is no write
privilege for group and others..
chgrp: Changing group owner
• This command changes the file‘s group owner. No super user permission is required.
$ls –l dept.lst
⚫ When you log on to a unix machine , you first see a prompt. Even though it may appear that
the system is idling, a UNIX command is running at the terminal. This command is the shell.
Even though the shell appears not to be doing anything meaningful when there is no activity
at the terminal, it swings into action the moment you key in something.
⚫ When a command is keyed in, it goes as input to the shell. The shell scans for metacharacters.
After pre-processing, the shell passes on the command line to the kernel for ultimate
execution. After the execution, the shell once again issues the prompt to take up your next
command
The following activities are typically performed by the shell in its interpretive cycle:
Department of CS&E, AJIET Page 11
UNIX PROGRAMMING 18CS56- Module 2
• The shell issues the prompt and waits for you to enter a command.
• After a command is entered, the shell scans the command line for meta characters and expands
abbreviations (like the * in rm *) to recreate a simplified command line. It then passes on the
command line to the kernel for execution.
• The shell waits for the command to complete and normally can’t do any work while the
command is running.
• After the command execution is complete, the prompt reappears and the shell returns to its
waiting role to start the next cycle. You are free to enter another command.
2.7 WILD-CARDS
A pattern is framed using ordinary characters and a meta character (like *) using well- defined rules.
The pattern can then be used as an argument to the command, and the shell will expand it suitably
before the command is executed. The meta characters that are used to construct the generalized
pattern for matching filenames belong to a category called wild-cards. The following table lists
them:
Wild-card Matches
? A single character
[x-z] A single character that is within the ASCII range of characters x and z [!ijk] A
[!x-z] A single character that is not within the ASCII range of the characters x and z (Not in C Shell)
The * and ?
⚫ To list all files whose filenames are six character long and start with chap, use ,
$ls chap??
chap01 chap03 chap15
Matching the dot
⚫ The * doesn’t match all files beginning with a . (dot) or the / of a pathname. ⚫ If you wish to
list all hidden filenames in your directory having at least three characters after the dot, the dot
must be matched explicitly.
$ ls .???*
.bash_profile .exrc .netscape
⚫ However, if the filename contains a dot anywhere but at the beginning, it need not be matched
explicitly.
$ ls emp*lst
emp.lst emp1.lst emp221lst emp2.lst
⚫ Similarly, these characters don’t match the / in a pathname. So, you cannot use,
$cd /usr?local to change to /usr/local.
⚫ For example,
⚫ To match all filenames with a single-character extension but not the .c or .o files, use *.[!co]
⚫ To match all filenames that don’t begin with an alphabetic character, use [!a-zA-Z]*
⚫ To copy all the c and java source program from another directory, Delimit the pattern with
comma, and then put ({}) curly braces around them (no space).
cp $HOME/prog_sources/*.{c,java}
⚫ To access multiple directories
cp home/kumar/{projects,html,scripts}
these copies all the three files from directories to the current directory(home/kumar/).
Rounding up
⚫ Some of the wild-card character have different meaning depending on where they are placed
in the pattern.
⚫ The * and ? loose their meaning when they are inside the class, and are matched literally.
Similarly, - and ! Also lose their significance when placed outside the class.
⚫ To summarize sample set of command line presented below:
ls *.c lists all files with .c extension
cp foo foo* copies foo to foo*(* loses meaning here)
cp ???? progs copies all files with 4 character names to
progs directory
⚫ Escaping - providing a \ (backslash) before the wild-card to remove (escape) its special
meaning.
⚫ Quoting - enclosing the wild-card, or even the entire pattern, within quotes.
2.8.1 Escaping
⚫ Escaping is providing a \ (backslash) before the wild-card to remove (escape) its special
meaning.
⚫ to remove the file, it is dangerous to give command as rm chap*, as it will remove all
files beginning with chap.
$cat chap0\[1-3\]
Escaping the space
⚫ A filename can contain a whitespace character also. Hence to remove a file named My
Document.doc
$ rm My\ Document.doc
⚫ Sometimes it is required to interpret the \ itself literally. You need another \ before it.
2.8.2 Quoting
Quoting is enclosing the wild-card, or even the entire pattern, within quotes. Anything within these
quotes (barring a few exceptions) are left alone by the shell and not interpreted. When a command
argument is enclosed in quotes, the meanings of all enclosed special characters are turned off.
⚫ Examples:
Here the pair of `` evaluated as null command and $TERM as vt100 inside double quotes
Example 2:-
⚫ The \ has a reverse meaning there, it treats the character n and t as special rather than remove
their special meanings.
⚫ These escape sequence is always used within the quotes to keep the shell out.
2.9 REDIRECTION: THE THREE STANDARD FILES
The shell associates three files with the terminal – two for display and one for the keyboard. These
files are streams of characters which many commands see as input and output. When a user logs in,
the shell makes available three files representing three streams. Each stream is associated with a
default device: -
Standard input: The file (stream) representing input, connected to the keyboard.
Standard output: The file (stream) representing output, connected to the display.
Standard error: The file (stream) representing error messages that emanate from the command or
shell, connected to the display.
Standard input:
When you use wc without an argument and have no special symbol like the < and | in the
command line, wc obtains its input from the default source. This input has to be provided from
the keyboard and mark the end of input.
$wc
Or a pipeline
[ctrl –d]
3 14 71
Shell can reassign the standard input file to a disk file. This means it can redirect the standard input
to originate from the file on the disk. This reassignment or redirection requires the < symbol.
3 14 71
⚫ It unplugs the standard input file from its default source and assigns it to sample.txt ⚫ wc
reads from standard input which has earlier been reassigned by the shell to sample.txt. Taking
⚫ When command takes input from multiple sources- say file and standard input, the – symbol
must be indicate the sequence of taking input. The meaning of the following sequence should
be quite obvious:
cat - foo // first from standard input and then from foo
cat foo - bar // first from foo and then standard input and then bar
Standard Output
All commands displaying output on the terminal actually write to the standard output file as a stream
of character, and no directly to the terminal. The standard output can represent three possible
destinations:
The shell can effect the redirection of this stream when its sees the > or >> symbols in the command
line. You can replace the default destination (the terminal) with any file by using >(right chevron)
operator, followed by the filename:
$cat newfile
3 14 71 sample.txt
The first command sends the word count of sample.txt to newfile; nothing appears on the terminal
screen. If the output file doesn’t exit, the shell creates it before executing the command.If it exist, the
shell overwrites it, so use this operator with caution. The shell also provides the >> symbol to
append the file:
⚫ On seeing the >, the shell opens the disk file, newfile, for writing.
⚫ It unplugs the standard ouput file from its default destination and assigns it to newfile.
⚫ wc writes to standard output which has earlier been reassigned by the shell to newfile.
Standard error
Each of the 3 standard files is represented by a number called file descriptor.A file is opened by
referring to its pathname, but subsequent read and write operations identify the file by this file
descriptor.The kernel maintains a table of file descriptors for every process running in the system
0- standard input
1- standard output
2– standard error
We need to explicitly use one of these descriptors when handling the standard error stream. When an
incorrect command is entered or if we try to open a non existing file, certain diagnostic messages are
shown on the screen.This is the standard error stream whose default destination is the terminal
$ cat foo
Here cat fails to open the file and writes to standard error
Standard error cannot be redirected in the same way of standard output, even though both uses
terminal as the default destination .Redirecting standard error requires the use of 2> symbols
cat errorfile
All commands don’t use the features of standard input and standard output.In this viewpoint UNIX
commands can be grouped into four categories viz.
• Directory-oriented commands like mkdir, rmdir and cd, and basic file handling commands like
cp, mv and rm use neither standard input nor standard output.
• Commands like ls, pwd, who etc. don’t read standard input but they write to standard output. •
Commands like lp that read standard input but don’t write to standard output. • Commands like
cat, wc, cmp etc. that use both standard input and standard output.
Commands in the fourth category are called filters. Note that filters can also read directly from files
whose names are provided as arguments.
Example:
To perform arithmetic calculations that are specified as expressions in input file calc.txt and redirect
the output to a file result.txt, use
$ cat calc.txt
2^32
25*50
30*25 + 15^2
We can redirect bc’s standard input to come from this file and save the output in yet another
$ bc < calc.txt > result.txt
$ cat result.txt
4294967296
1250
975
bc obtained the expression from redirected standard input, processed them and sent out the result to a
redirected output stream.Though we used < first and then >, there is no restriction in the sequence
we use or in the use of whitespaces around it.
bc > result.txt < calc.txt
bc>result.txt<calc.txt
Department of CS&E, AJIET Page 19
UNIX PROGRAMMING 18CS56- Module 2
Pipes
With piping, the output of a command can be used as input (piped) to a subsequent command.
$ command1 | command2
⚫ For example :- who command produces a list of users
In order to count the number of lines in the above output, we need to redirect this output to a file
$ who > user.txt
Now wc command is used to count the number of lines only
$wc -l < user.txt
5
Using an intermediate file(user.txt) , we counted the number of users. The 2 disadvantages of using
intermediate file are:-
• Process can be slow, second command cant act unless the fist has completed its job •
Intermediate file has to be removed after completion of the job
The shell can connect these streams using a special operator, the |(pipe) and avoid the creation of
disk file.
$ who | wc –l
5 //no intermediate file is created
Here the output of who has been passed directly to the input of wc, and who is said to be piped to wc
.
Examples
$ ls -l | wc –l Displays number of file in current directory $ who | wc –l
Displays number of currently logged in users
Creating a tee
tee is an external command that handles a character stream by duplicating its input. It saves one copy
in a file and writes the other to standard output. It is also a filter and hence can be placed anywhere
in a pipeline.
Example:- The following command sequence uses tee to display the output of who and saves this
output in a file as well.
$who | tee users.lst
root console aug 1 07:51 (:0)
kumar pts/10 aug 1 02:51 (:0)
sharma pts/6 aug 1 03:51 (:0)
Above command displays currently logged in users on standard output and writes a copy to users.lst
grep searches for pattern in one or more filename or the standard input if no filename is specified.
The first argument(barring the options) is the pattern and the remaining arguments are filenames.
⚫ Grep is also a filter, it can search its standard input for the pattern, and saves the standard
output in a file
$ who | grep kumar> foo
⚫ When grep is used with multiple filenames it displays the filenames along with the output
gr
ep options:
The below table shows all the options used by grep.
Option Significance
⚫ Used to search all lines containing a pattern regardless of uppercase and lowercase distinction
Deleting lines(-v)
The –v option selects all lines except those containing the pattern
The lines containing the pattern director are deleted in the output
The –n option displays the line numbers containing the pattern along with the line
Counting lines containing patter(-c)
The –c option counts the number of lines containing the pattern.
Dislayingfilenames(-l)
The –l option displays only the names of the files containing the pattern. Here the pattern manager is
searched in all files ending with .lst (*.lst)
expressions(BRE) by default and extended regular expression with –E option. The below table
shows the BASIC REGULAR EXPRESSION(BRE) character set
The *
The * (asterisk) refers to the immediately preceding character.
Here, it indicates that the previous character can occur many times, or not at all.
$ grep '[aA]gg*[ar][ar]wal' emp.lst
The Dot
A . matches a single character. The pattern 2... matches a four-character pattern beginning with a 2.
The shells equivalent pattern is 2???. The pattern .* matches any number of characters, or none.
$ grep 'j.*saxena' emp.lst
2345 |j. b. saxena |g. m. |marketing |12/03/45|8000
Ex 2:-To select the lines where salary is between 7000 and 7999
$ grep '7...$' emp.lst
9876|jai sharma |director |production |12/03/50|7000
2365|barun sengupta |director |personnel |11/05/47|7800
3564|sudhir Agarwal |executive |personnel |06/07/47|7500
The + and ?
Incase for a string like #include<stdio.h>, if we don’t know how many spaces to give , use the
following expression:
#include +<stdio.h>
# ?include +<stdio.h>
SHELL PROGRAMMING
• A shell script contains a list of commands which have to be executed regularly. Shell script is
also known as shell program. The user can execute the shell script itself to execute
commands in it.
• A shell script runs in interpretive mode. i.e. the entire script is compiled internally in memory
and then executed. Hence, shell scripts run slower than the high-level language
programs.".sh" is used as an extension for shell scripts.
• Example: A shell script (program1.sh) to execute few commands.
#!/bin/sh
echo “Welcome to Shell Programming” # print message
echo “Today’s date : `date`” # print date
echo “My Shell :$SHELL” # print shell name
• The hash symbol # indicates the comments in the script. The shell ignores all the characters
that follow the # symbol. However, this does not apply to the first line.
• The first line "#! /bin/sh" indicates the path where the shell script is available.
• By default, script is not executable. So, the chmod command can be used to make the script
executable.
• The child shell reads and executes each statement in interpretive mode.
Run:
$ chmod +x program1.sh // add executable permission
$ program1.sh // execute the script program1.sh
Output:
Welcome to Shell Programming
Today’s date: Mon Nov 4 11:02:45 IST 2017
My Shell: /bin/sh
2) Execute Shell Script by Specifying the Interpreter
The user can also execute a shell script by specifying the interpreter in the command line. Here,
the script neither requires a executable permission nor an interpreter line.
Run:
$ sh program1.sh //Execute using sh interpreter
$ bash program1.sh //Execute using bash interpreter
Output:
Welcome to Shell Programming
Today’s date: Mon Nov 4 11:02:45 IST 2017
My Shell: /bin/sh
• ordinary variable
Environment variables
• Environment variable Environment variables control the behavior of the system. They
determine the environment in which user work. If environment variables are not set properly,
the users may not be able to use some commands.
• Environment variables are so called because they are available in the user's total environment
i.e. the sub-shells that run shell scripts and mail commands and editors. • Some variables are set
by the system, others by the users, others by the shell programs.
• For example:
$ env
HOME=home/kumar
IFS=' '
LOGNAME=kumar
MAIL= /var/mail/kumar
MAILCHECK=60
PATH=/bin:/usr/bin
PS1='$'
PS2='>'
SHELL=/usr/bin/bash
TERM= tty1
• HOME:- This variable indicates the home directory of the current user.This variable is set for
a user by the system admin in /etc/passwd.
• IFS:-This variable contains a string of characters that are used as word separator in the
command line. The string normally consists of the space, tab and newline characters. •
LOGNAME:- This variable shows the username.
• MAIL:-This variable specifies the path to user’s mailbox.
• MAILCHECK:-This variable determines how often the shell checks the file for the arrival of
new mail.
• PATH:-This variable specifies the locations in which the shell should look for commands.
Usually, the PATH variable can be set as follows:
o $PATH=/bin:/usr/bin
• SHELL:-This variable specifies the current shell being used by the users.Different types of
shells are: Bourne shell /bin/sh
▪ C-shell /bin/csh
• TERM:-This variable indicates the terminal type that is used.Every terminal has certain
characteristics that are defined in a separate control file in the terminfo directory. If TERM is
not set correctly, vi will not work and the display will be faulty
Ordinary Variable
A variable is a character string to which the user assigns a value.The value assigned can be a
number, text, filename, device, or any other type of data.
Syntax:
variable = value // variable definition
The value of variables are stored in the ASCII format.
For example:
$ x=50
$ echo $x //displays 50
In command line, all words that are preceded by a $ are identified and evaluated as variables. A
variable can be removed with unset and protected from reassignment by readonly. Both are shell
internal commands.
$ set count=5
$ readonly size = 10
The variables exist only for a short time during the execution of a shell script. As the variables are
defined and used by specific users, they are also called user-defined variables.
Uses of Local variables
• Setting pathnames: If a pathname is used several times in a script, we can assign it to a variable
and use it as an argument to any command.
• Using command substitution: We can assign the result of execution of a command to a
variable. The command to be executed must be enclosed in backquotes.
• Concatenating variables and strings: Two variables can be concatenated to form a new variable.
Example:
$ base=foo ; ext=.c
$ file=$base$ext
$ echo $file // prints foo.c
• A specific file for each individual user with responsibility for the user environment. •
A universal file for all users with responsibility for the general environment.
The user can view his ".profile" as follows:
• read command can be used for taking input from the keyboard.It is shell’s internal tool for
making scripts interactive.
• Syntax:
▪ read var_name
• It is used with one or more variables.The variables are used to hold inputs given with the
standard input.
Read
Only
Readonly command can be used to make variables readonly, the user cannot change the value of
variables.
Syntax : variable =value
Example:-
$ readonly pi=3.14
$ echo $pi //displays 3.14
$ pi=6.12 //this will result in error
$? Stores the exit status of the last command that was executed.
$$ Stores PID of the current shell
Example: A shell script to read and display various shell parameters from the command line.
#!/bin/sh
Numeric Comparison
Numerical Comparison operators used by test:
Operator Meaning
-eq Equal to
output
1 # x Not Equal to y
0 #True; 5<7
0 #true 5!=7
1 #false
SHORTHAND FOR TEST :-
A pair of rectangular brackets enclosing the expression can replace the term test. Hence, above
example may be re-written as
test $x -eq $y
or
[ $x -eq $y ] #Both are equivalent
Provide whitespace around the operators, operands and inside the [ and ].
String Comparison
Test can be used to compare strings with yet another set of operators. The below table shows string
tests used by test
Test True if
s1 = s2 String s1 = s2
s1 != s2 String s1 is not equal to s2
-n stg String stg is not a null string
-z stg String stg is a null string
stg String stg is assigned and not a null string
s1 == s2 String s1 = s2 (Korn and Bash only)
Example:-a shell script to check whether 2 strings are equal
#!/bin/sh
echo “Enter the first string: \c”
read str1
if [ -z “$str1” ] ; then
echo “You have not entered the string”; exit 1
echo “Enter the second string: \c”
read str2
• Test command can be used to check various file attributes such as file type (-, d or l) & file permission (r,
w, x).
Department of
Output :-
2.19 The If
The if statement makes two-way decisions depending on the fulfilment of a certain condition. In the
shell, the statement uses the following forms
if command is successful then execute commands If command is successful then
execute commands else fi execute commands fi
If command is successful then execute commands elif command is execute commands else
successful then execute commands fi
Form 1 Form 2 Form 3
• Example: A script to test a user response for YES, yes, Yes, yEs (or no, NO, No, nO).
#! /bin/sh
echo “Do you wish to continue? [y/n]:”
read ans
case “$ans” in
[Yy] [eE]* ) ;; # Matches YES, yes, Yes, yEs, etc
[Nn] [oO] ) exit ;; # Matches no, NO, No, nO
* ) echo “Invalid Response”
esac
Examples:
$ expr 3 + 5 //outputs 8
$ x=8 y=4
$ expr $x + $y //outputs 12
$ expr $x - $y //outputs 4
$ expr $x \* $y //32 Asterisk(*) has to be escaped to prevent from metacharacter $
expr $x / $y //outputs 2
$ expr $x % $y // outputs0
expr is often used with command substitution to assign a variable.
For example, you can set a variable z to the sum of two numbers:
$ x=6 y=2; z=expr `$x + $y`
$ echo $z
8
String Handling
For manipulating strings, expr uses two expressions separated by a colon.
The string to be worked upon is placed on the left of the colon (:) and regular expression is placed on
its right. Depending on the composition of the expression, expr can perform three important string
functions:
• Determine the length of the string
• Extract a substring
• Locate the position of a character in a string
The regular expression ".*" is used to print the number of characters matching the pattern.
• Example:
expr command can be used to extract a string enclosed by the escape characters "\(" and"\)".
• Example:
expr command can be used to find the location of the first occurrence of a character inside a
• Example:
$ expr “vtunotesbysri” : "[^u]*u" // outputs 3
NOTE:
The shell also offers an until statement which operates with a reverse logic used in while. With until,
the loop body is executed as long as the condition remains false.
$ wc -l << END
Decide
Commit
Succeed
END
3 //outputs number of lines = 3
• Ignore signals
A script can be made to ignore a specific signal by using a null command list
Ex:- trap ‘ ‘ SIGINT
2. Shell script that accepts two file names as arguments, checks if the permissions for these
files are identical and if permissions are identical outputs the common permission,
otherwise outputs each file name followed by its permissions
#!/bin/bash
echo "enter the filenames:"
read f1 f2
file1=`ls -l $f1|cut -c 1-10`
x=0
while [$x –le 10];
do
echo “$x \t”
x=`expr $x+1`
done
4.Shell script to check the regular files in a current directory
#!/bin/sh
for i in ~/*
do
if [ -f $i ]
then
echo " $i is a regular file "
else
echo " $i is not a regular file "
fi
done
Departm
ent of CS&E, AJIET Page 49
UNIX PROGRAMMING 18CS56- Module 2
7. A shell script to read a pattern and filename from the terminal. And search for the pattern
in the file.
#! /bin/sh
echo “Enter the pattern to be searched: \c”
read pname
echo “Enter the file to be used: \c”
read fname
echo “Searching for pattern $pname from the file $fname”
grep $pname $fname
echo “Selected records shown above”
8. A shell script to compute sum of numbers passed in command line
#!/bin/sh
sum=0
for I in “$@”
do
sum =`expr $sum + $I`
done
echo “sum is $sum”
Questions
1. Explain while and for with syntax.
2. Explain ls-l Command with its attributes.
3. With example explain set and shift commands and handling positional parameters.
4. Explain shells interpretive cycle.
5. Explain grep, egrep and list its option with significance
6. Explain three standard files supported by unix and Also give details about special file used for
redirection in unix
7. Explain here document and trap command
8. Explain how to change file permission
9. What do you mean by wild cards
10. Write a shell script to find the sum of n given number using for and while
loop 11. Write a shell script to check whether the given number is paliandrome or
not