Module - 2 - Unix System Programming (BCS515C)
Module - 2 - Unix System Programming (BCS515C)
)
R. L. JALAPPA INSTITUTE OF TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to VTU, Belagavi & Accredited by NAAC “A” Grade)
Kodigehalli, Doddaballapur- 561 203
Department of CS&E (Artificial Intelligence & Machine Learning)
Institute Mission
M1: To provide an outstanding Teaching, Learning and Research environment through Innovative Practices
in Quality Education.
M2: Develop Leaders with high level of Professionalism to have career in the Industry, Zeal for Higher
Education, focus on Entrepreneurial and Societal activities.
Department Vision
To empower the students with knowledge and skills to develop the competency in the field of Artificial
Intelligence and Machine Learning.
Department Mission
M1: To craft the students with Novel and Intellectual skills to capability in the field of Artificial Intelligence
and Machine Learning.
M2: To train the students to have Professional career in the field of AI and ML and zeal for Higher Studies
and Research.
PROGRAMME SPECIFIC OUTCOMES (PSOs)
PSO1: Students will have the ability to understand analyse and demonstrate the knowledge of Human
cognition, Artificial Intelligence, Machine Learning in terms of real world problems to meet the challenges
of future.
PSO2: Students will have the knowledge of software, Hardware, Algorithms, Modelling Networking and
Application Development.
PSO3: Students will have the ability to develop computational knowledge using Innovative tools and
techniques to solve problems in the areas related to Machine learning and Artificial Intelligence.
Module 2
File type and Permissions:The first column shows the type and permissions
associated with each file. 3 types of file
Ordinary file( - )
Directory file (d)
Device file(a,b or c)
3 types of permission
r -> read
w -> write
x -> execute
Links :The second column indicates the number of links associated with the file.
Ownership: When you create a file, you automatically become its owner.
Group Ownership: Every user is attached to a group owner
File size: File size in bytes
Last modification time and date:If you change only the permissions or ownership of
the file, the modification time remains unchanged
File name:Displays file name.
Example: $ ls –l
total 72
- rw - r- - r- - 1 kumar metal 19514 may 10 13:45 chap01
- rw - r- - r- - 1 kumar metal 4174 may 10 15:01 chap02
- rw - rw - rw - 1 kumar metal 84 feb 12 12:30 dept.lst
1. File ownership
When you create a file, you become its owner (third column)
Group owner of the file (fourth column)
Several users may belong to a single group, but the privileges of the group are set by
the owner of the file and not by the group members
When the system administrator creates a user account, he has to assign these
parameters to the user:
The user-id (UID) – both its name and numeric representation
The group-id (GID) – both its name and numeric representation
The file /etc/passwd and /etc/group contains the UID and GID
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)
Example:
- rwx r-x r-- 1 kumar metal 20500 may 10 19:21 chap02
rwx r-x r--
owner/user group owner others
Each group here represents a category and contains three slots, representing the read,
write and execute permissions of the file
3 types of categories
Owner(user): (rwx)
It contains all three permissions(rwx).
The file is readable, writable and executable by the owner of the file.
group :(r – x)
Group has a hyphen in the middle slot, which indicates the absence of
write permission by the group owner of the file.
Other: (r - -)
It 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.
1. Relative Permissions
chmod only changes the permissions specified in the command line and the other
permissions unchanged.
syntax
chmod category operation permission filename(s)
Initially,
-rw-r--r-- 1 kumar metal 1906 sep 23:38 priya
$ chmod u+x priya ; ls –l priya
2 Absolute Permissions
Here, we need not to know the current file permissions.
We can set all nine permissions 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.
Example:
Using absolute permission, we have,
will assign all permissions to the owner, read and write permissions for the group and
only execute permission to the others.
using chmod Recursively(-R)
chmod -R a+x shell_scripts
This makes all the files and subdirectories found in the shell_scripts directory, executable
by all users.
Directory Permissions
It is possible that a file cannot be accessed even though it has read permission, and can be
removed even when it is write protected.
If a directory has write permission for group and others also, be assured that every
user can remove every file in the directory.
As a rule, you must not make directories universally writable unless you have
definite reasons to do so.
If sharma copies a file of kumar, then sharma will become its owner and he can
manipulate the attributes
Thus, Kumar can no longer edit note since there is no write privilege for group and
others. He cannot get back the ownership either. But he can copy the file to his own
directory, in which case he becomes the owner of the copy.
The * and ?
The metacharacter * is one of the characters of the shell’s wild-card set. It matches any number
of characters (including none).
Example: To list all files begin with chap, use
$ ls chap*
chap chap01 chap02 chap03 chap04 chap15 chap17 chapx chapy chapz
The next wild-card is the ? which matches a single character.
Example: To list all files whose filenames are five character long and start with chap, use
$ ls chap?
chapx chapy chapz
Example: To list all files whose filenames are six character long and start with chap, use
$ ls chap??
chap01 chap02 chap03 chap04 chap15 chap17
Note: There are two things that the * and ? Can’t match.
They don’t match a filename beginning with a dot, but they can match any number of embedded
dots.
They don’t match the / in a pathname.
Hence both a dot (.) and / must be matched explicitly.
The character class
The character class comprises a set of characters enclosed by the rectangular brackets [ and ],
but it matches a single character in the class.
The pattern [abd] is character class, and it matches a single character- a, b or d.
Example:
$ ls chap0[124] matches chap01, chap02 and chap04
$ ls chap[1-4] matches chap1, chap2, chap3 and chap4
$ ls chap[x-z] matches chapx, chapy and chapz
You can reverse the matching criteria by using ! As the first character in the class.
$ ls *.[!co] matches all filenames with a single-character extension but not .c
and .o (Not in C Shell)
To summarize
Quoting: Enclosing the wild-card, or even the entire pattern, within quotes. When a command
argument is enclosed in quotes, the meanings of all enclosed special characters are turned off.
Example:
$ rm ‘chap*’ Removes file chap*
Standard Output
All commands displaying output on the terminal actually write to the standard output file as a
stream of characters. There are three possible destinations of this stream:
The terminal, the default destination
A file using the redirection symbols > and >>
As input to another program using a pipeline
Example:
wc sample.txt
wc sample.txt > outputFile
who | wc –l
cat *.c > all_C_progs.txt
Standard Error
When you enter an incorrect command, or try to open nonexistent file, certain diagnostic
messages show up on the screen. This is the standard error stream.
For example, trying cat on a nonexistent file produces the error stream.
We can redirect this stream to a file. But, standard error cannot be redirected in the same way
standard output can be (with > or >>). To capture the standard error and redirect to a file we
have to use 2> symbols.
Example: cat file1 2> errorfile
cat file2 2>> errorfile
Filters: Using both standard input and standard output
UNIX commands can be grouped into 4 categories viz.,
1. 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.
2. Commands like ls, pwd, who etc. don’t read standard input but they write to standard
output.
3. Commands like lp that read standard input but don’t write to standard output.
4. Commands like cat, wc, bc etc. that use both standard input and standard output.
The commands in fourth category are called filters. When a program/command performs
operations on input and writes the result to the standard output, it is called a filter.
Example: $ bc < expressions.txt > results.txt
The following command sequence uses tee to display the output of who and saves this output
in a file as well:
$ who | tee user.txt
romeo pts/2 sep 7 08:41 (pc123.heavens.com)
juliet pts/3 sep 7 08:41 (pc123.heavens.com)
Sumit pts/2 sep 7 08:41 (mercury.heavens.com)
user.txt also contains this output.
Command substitution
Any command surrounded by backquotes is executed by the shell, which then replaces the
standard output of the command into the command line.
While a pipe enables a command to obtain its standard input from the standard output of another
command, the shell enables one or more command arguments to be obtained from the standard
output of another command. This feature is called command substitution.
Example:
$ echo Current date and time is `date`
Current date and time is Mon Oct 30 09:35:16 IST 2017
Observe the use of backquotes around date in the above command. Here the output of the
command execution of date is taken as argument of echo. The shell executes the enclosed
command and replaces the enclosed command line with the output of the command.
$ echo “There are `ls | wc –l` files in the current directory”
There are 47 files in the current directory
The backquote is not interpreted by the shell if enclosed in single quotes.
$ echo ‘There are `ls | wc –l` files in the current directory’
There are `ls | wc –l` files in the current directory
Command substitution has interesting application possibilities in shell scripts. It speeds up
work by letting you combine a number of instructions in one.
Korn Shell, Bash Shell
POSIX recommends the use of the form $(command) rather than the old `command` for
command substitution. The Korn shell and Bash shell offer both forms.
$ echo The date today is `date` OR
$ echo The date today is $(date)
Shell variables
Environmental variables are used to provide information to the programs you
use. You can have both global environment and local shell variables.
Global environment variables are set by your login shell and new programs and
shells inherit the environment of their parent shell.
Local shell variables are used only by that shell and are not passed on to other
processes. A child process cannot pass a variable back to its parent process.
Some global environment variables are,
C Shell
Group of commands have to be executed regularly, they should be stored in a file and
file itself executed as a shell script or a shell program by the user.
A shell program runs in interpretive mode.
Shell scripts are executed in a separate child shell process which may or may not be
same as the login shell.hell Scripts/Shell Programs
Example: script.sh
#! /bin/sh
The # character indicates the comments in the shell script and all the characters that follow
the # symbol are ignored by the shell. However, this does not apply to the first line which
beings with #.
This because, it is an interpreter line which always begins with #! followed by the pathname
of the shell to be used for running the script. In the above example the first line indicates that
we are using a Bourne Shell.
To run the script we need to first make it executable. This is achieved by using the chmod
command as shown below:
$ chmod +x script.sh
$ sh script.sh
The .profile
the .profile lets you to customize your operating system environment to suit your
requirements.
This environment remains in effect throughout the login session.
Every time you make changes to this file.. You should either logout and login again,or
use special command to execute file:
$ .profile
The read statement is the shell’s internal tool for making scripts interactive (i.e. taking input
from the user). It is used with one or more variables. Inputs supplied with the standard input
are read into these variables. For instance, the use of statement like
read name
causes the script to pause at that point to take input from the keyboard. Whatever is entered
by you will be stored in the variable name.
Example: A shell script that uses read to take a search string and filename from the
terminal.
#! /bin/sh
read pname
read fname
Output
$ sh emp1.sh
Shell scripts also accept arguments from the command line. Therefore they can be run
non interactively and be used with redirection and pipelines.
The arguments are assigned to special shell variables. Represented by $1, $2, etc
Similar to C command arguments argv[0], argv[1], etc. The following table lists the
different shell parameters.
$# Number of arguments specified in command line
C program and shell scripts have a lot in common, and one of them is that they both use the
same command to terminate a program.
It has exit in shell and exit( ) in C.
There are two very common exit values
exit 0 successful
exit 1 failure
Example:
$ cat foo
cat: can’t open foo
Returns nonzero value to the calling program
The shell offers a variable $? And a command (test) that evaluates the exit status.
The shell provides two operators that allow conditional execution, the && and ||.
Usage:
cmd1 && cmd2
cmd1 || cmd2
&& delimits two commands. cmd 2 executed only when cmd1 succeeds.
Example1:
|| this indicates inverse role , the second command executed only first command fails
Example 2:
$ grep ‘clerk’ emp.lst || echo “Pattern not found”
Output:
Pattern not found
Numeric comparison in the shell is confined to integer values only, decimal values are
simply truncated
Example:
$x=5;y=7;z=7.2
1. $test $x –eq $y; echo $?
1 Not equal
2. $test $x –lt $y; echo $?
0 True
3. $test $z –gt $y; echo $?
1 7.2 is not greater than 7
4. $test $z –eq $y ; echo $?
0 7.2 is equal to 7
The if Conditional
The if statement makes two way decision depending on the fulfillment of a certain condition.
Form 1:
if command is successful
then
execute commands
else
execute commands
fi
Form 2:
if command is successful
then
execute commands
fi
Form 3:
if command is successful
then
execute commands
elif commands is successful
then . . .
else . . .
fi
Example:
#! /bin/sh
if grep “^$1” /etc/passwd 2>/dev/null
then
echo “Pattern Found”
else
echo “Pattern Not Found”
fi
String Comparison:
Test command is also used for testing strings. Test can be used to compare strings with the
following set of comparison operators as listed below.
Example:
#!/bin/sh
#emp1.sh checks user input for null values finally turns emp.sh developed previously
#
if [ $# -eq 0 ] ; then
echo “Enter the string to be searched :\c”
read pname
if [ -z “$pname” ] ; then
echo “You have not entered the string”; exit
fi
echo “Enter the filename to be used :\c”
read flname
if [ ! –n “$flname” ] ; then
echo “ You have not entered the flname” ; exit
fi
grep “$pname” $flname
fi
Output1:
$emp1.sh
Enter the string to be searched :[Enter]
You have not entered the string
Output2:
$emp1.sh
Enter the string to be searched :root
Enter the filename to be searched :/etc/passwd
Root:x:0:1:Super-user:/:/usr/bin/bash
File Tests
test can be used to test various file attributes like its type (file, directory or symbolic
links)
its permission (read, write. Execute, SUID, etc).
the following table depicts file-related tests with test
Example:
$ ls –l emp.lst
-rw-rw-rw- 1 kumar group 870 jun 8 15:52 emp.lst
Commands
done
Example:
for file in ch1 ch2
do
cp $file ${file}.bak
echo $file copied to $file.bak
done
Output:
ch1 copied to ch1.bak
ch2 copied to ch2.bak
Sources of list:
List from variables: Series of variables are evaluated by the shell before executing the loop
Example:
$ for var in $PATH $HOME;
do
echo “$var” ;
done
Output:
/bin:/usr/bin;/home/local/bin;
/home/user1
List from command substitution: Command substitution is used for creating a list. This is
used when list is large.
Example:
$ for var in `cat clist`
List from wildcards: Here the shell interprets the wildcards as filenames.
Example:
for file in *.htm *.html ; do
sed ‘s/strong/STRONG/g
s/img src/IMG SRC/g’ $file > $$
mv $$ $file
done
List from positional parameters:
Example: emp.sh
#! /bin/sh
for pattern in “$@”; do
grep “$pattern” emp.lst || echo “Pattern $pattern not found”
done
While: looping
It repeatadly performs a set of instructions until the control command returns a true exit status
Syntax:
while condtion is true
do
commands
done
Example:
#! /bin/bash
#shows use of while
#program to accept code and description in one line
answer=y
while [ "$answer" = "y" ]
do
echo "enter the code and description" > /dev/tty
read code description
echo "$code|$description" >> newlist #append this line to newlist
echo "enter anymore (y/n)?" >/dev/tty
read anymore
case $anymore in
y*|Y*) answer=y;; #also accept yes,YES
n*|N*)answer=n;; #also accept no|NO
*)answer=y;; #any other reply mean y
esac
done
Syntax:
case expression in
Pattern1) commands1 ;;
Pattern2) commands2 ;;
Pattern3) commands3 ;;
…
esac
case first matches expression with pattern1. If the match succeeds, then it executes
commands1, which may be one or more commands. If the match fails, then pattern2 is
matched and so forth. Each command list is terminated with a pair of semicolon and the
entire construct is closed with esac (reverse os case).
Example: Write a shell program to create a menu which displays i) List of files
ii) Process of user iii) Today’s Date iv) users of system v) Quit to UNIX
#! /bin/sh
#
echo “Menu\n1. List of files\n2. Processes of user\n3. Today’s Date
4. Users of system\n5.Quit\nEnter your option: \c”
read choice
case “$choice” in
1) ls –l;;
2) ps –f ;;
3) date ;;
4) who ;;
5) exit ;;
*) echo “Invalid option”
esac
Output:
$ menu.sh
Menu
1. List of files
2. Processes of user
3. Today’s Date
4. Users of system
5. Quit
Enter your option: 3
Mon Nov 6 09:02:45 IST 2017
set and shift: Manipulating the Positional Parameters
The set statement assigns positional parameters $1, $2 and so on, to its arguments. This is
used for picking up individual fields from the output of a program.
Example 1: $ set 9876 2345 6213
This assigns the value 9876 to the positional parameters $1, 2345 to $2 and 6213 to $3
Shift: Shifting Arguments Left
Shift transfers the contents of positional parameters to its immediate lower numbered one. This
is done as many times as the statement is called. When called once, $2 becomes $1, $3 becomes
S2 and so on
Example 1:
$ echo “$@” $@ and $* are interchangeable
Mon Oct 8 08:02:45 IST 2007
$ echo $1 $2 $3
Mon Oct 8
$ shift
$ echo $1 $2 $3
Oct 8 08:02:45
> emp.lst
> END
Output:
Enter the pattern to be searched: Enter the file to be used: Searching for director from file
emp.lst
9876 Jai sharma Director Productions
2356 Rohit Director Sales
Selected records shown above.
Assignment Questions
1. Explain the seven field output of ls –l command. Or Explain briefly the file
attributes listed using ls –l command. Or Which command is used for listing file
attributes? Explain significance of each field of the output.
2. What are different ways of setting file permissions? Or Explain how to use chmod
command to set the permissions in a relative and absolute manner with an example.
3. A file’s current permissions are – r w - r- - r- - specify the chmod expression required
to change them for the following:
i) rwxrwxrwx
ii) r - - r - x r - -
iii) - - - - - - - - -
iv) - - - r - - r - -
Using both the relative and absolute methods of assigning permissions.
4. What are directory permissions?
5. Explain Shell’s interpretive life cycle.
6. What are wild cards? Explain the shells wild cards, with examples.
7. Discuss the three standard files supported by UNIX. Or explain the standard input,
standard output and standard error with respect to UNIX operating system.
8. Explain the following
i) Filters ii) pipe iii) tee iv) Command substitution
9. Explain grep command with its options.
10. Explain with example Basic Regular Expressions (BRE).
11. Explain the anchoring characters.
12. What are environment variables? Explain any four. OR
Explain the following environment variables with examples:
i) SHELL ii) LOGNAME iii) PATH iv) HOME
13. What is the exit status of a command and where is it stores?
14. Explain the different ways of using test statements, with examples or Explain the use
of test and [ ] to evaluate an expression in shell.
15. What is shell script? Explain the following statements with syntax and examples.
i) if ii) case iii) while
16. Explain the shell features of “while” and “for” with syntax.
17. Explain the shell’s for loop giving the possible sources of the list.
18. Briefly explain set and shift commands in UNIX to manipulate positional
parameters with example.
19. Discuss use of trap statement for interrupting a program in UNIX.
20. What is shell programming? Write a shell program to create a menu which displays,
i) List of files ii) Current date iii) Process status
iv) Current user of the system and v) Quit to UNIX