3-1 Unix PPTS
3-1 Unix PPTS
• Return
• 0 on success.
• -1 on error.
lseek
• The UNIX system file system treats an ordinary
file as a sequence of bytes. Generally, a file is
read or written sequentially -- that is, from
beginning to the end of the file.
• Syntax: -
• #include<sys/types.h>
• #include<sys/stat.h>
• int fstat(int fd, struct stat *buff);
• fstat() retrieves information about the file
opened with file descriptor fd into the stat
structure pointed to by ‘buff’.
• lstat(): - The lstat() function is similar to the
stat() function, that is, it is also used to access
the information about a named file.
Syntax: -
• #include<sys/types.h>
• #include<sys/stat.h>
• int lstat(const char *filename, struct stat
*buff);
• The lstat() retrieves the information about the
filename into a stat structure pointed to by
buff.
• Description: -
• The argument d must be an open file
descriptor.
• The second argument is a device-dependent
request code.
• The third argument is an untyped pointer to
memory. It’s traditionally char *argp (from the
days before void * was valid C)
dup and dup2 system calls
• dup(): - The dup() system call creates a copy of
a file descriptor.
• Syntax: -
#include <unistd.h>
int link(const char *oldpath, const char
*newpath);
• Description: -
• If newpath exists it will not be overwritten.
This new name may be used exactly as the old
one for any operation; both names refer to
the same file (and so have the same
permissions and ownership) and it is
impossible to tell which name was the
`original’.
• Return Value: - On success, zero is returned.
On error, -1 is returned, and errno is set
appropriately.
• Syntax: -
#include <unistd.h>
int unlink(const char *pathname);
Description
• unlink() deletes a name from the file system.
• $ kill -1 1001
• $ kill -9 1001
• Syntax:-
date *OPTION+ … *+FORMAT+
Syntax:- $ stty
$ man –k sort
• If you want to know what UNIX sort utilities
are available, you can enter the command and
get a list of sort utilities.
• $ lpr file1
• The command prints one file to the standard
printer.
• $ passwd
Department of Information technology 168
Department of Information technology 169
10. Clear Screen (clear)
• The clear command clears the screen and puts
the cursor at the top.
• It is available in most systems.
Syntax:-
• $ clear
Syntax: -
• $uname
$uname –r
Output:
Syntax:-
fp=fopen(“data.txt”,”w”);
fp=fopen(“data.txt”,”a”);
fp=fopen(“data.txt”,”w+”);
Here, data.txt file is open for reading and
writing operation.
• a+(append+read):- In this file operation mode
the contents of the file can be read and
records can be added at the end of file.
• Syntax:-
fclose(file_pointer);
• To close one or more files at a time the
function fcloseall() is used.
• Syntax:-
fcloseall();
• FILE I/O:-
• After opening the file, the next thing needed
is the way to read or write the file. These
functions are classified as:-
• Syntax:-
fgetc(FILE *stream);
• fputc():- This function is used to write a single
character into a file. If an error occurs it
returns EOF.
• Syntax:-
• fputc(ch, FILE *stream);
• String I/O functions:-
• Syntax:-
fgets(str, size, FILE *stream);
• Syntax:-
• fputs(str,FILE *stream);
• Formatted I/O functions:-
• If the file contains data in the form of digits,
real numbers, character and strings, then
character I/O functions are not enough as the
values would be read in the form of
characters.
– fprintf()
– fscanf()
• These functions are used for formatted input
and output. These are identical to scanf() and
printf().
• fprintf():- This function is used for writing
characters, strings, integers, floats etc to the
file.
• Syntax:-
• fread(&structure_variable, int size, int
num,FILE *fp);
• Here, structure_variable is the pointer or
address of block of memory (structure).
• Syntax:-
• Parameters: -
stream − This is the pointer to a FILE object
that specifies a buffered stream.
• Return Value: -
• This function returns a zero value on success.
If an error occurs, EOF is returned and the
error indicator is set (i.e. feof).
Starting new process
• When you start a process (run a command),
there are two ways you can run it −
Foreground Processes
Background Processes
Foreground Processes
• By default, every process that you start runs in
the foreground.
• $ps
PID TTY TIME CMD
18358 ttyp3 00:00:00 sh
18361 ttyp3 00:01:31 abiword
18789 ttyp3 00:00:00 ps
• One of the most commonly used flags for ps is
the -f ( f for full) option, which provides more
information
• There are other options which can be used
along with ps command
Stopping Processes
• Ending a process can be done in several
different ways.
• $ps -f
• $kill 6738
Terminated
• Here, the kill command terminates
the first_one process.
• $kill -9 6738Terminated
Zombie and Orphan Processes
• Normally, when a child process is killed, the
parent process is updated via a SIGCHLD
signal.
• Daemon process
Process Control
Process Identifiers
o Opens an empty text line for new text after the current line.
O Opens an empty text line for new text before the current line.
Command Function
• Syntax: -
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
DIR *fdopendir(int fd);
• Description: -
• Syntax: -
#include <linux/types.h>
#include <linux/dirent.h>
int readdir(unsigned int fd, struct dirent
*dirp, unsigned int count);
• Return Value: -
• On success, 1 is returned. On end of directory,
0 is returned. On error, -1 is returned,
and errno is set appropriately.
• rewinddir(): - The rewinddir() function
rewinds , that is, reposition the pointer at the
first entry in the directory.
• Syntax: -
#include <sys/types.h>
#include <dirent.h>
void rewinddir(DIR *dirp);
• Description: - The rewinddir() function resets
the position of the directory stream dirp to
the beginning of the directory.
• Return Value: -
The rewinddir() function returns no value.
• closedir(): - The closedir() function closes the
directory passed to it.
• Syntax: -
#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);
• Description: -
• The closedir() function closes the directory
stream associated with dirp. A successful call
to closedir() also closes the underlying file
descriptor associated with dirp. The directory
stream descriptor dirp is not available after
this call.
• Syntax: -
#include <sys/stat.h>
#include <sys/types.h>
int mkdir(const char *pathname, mode_t
mode);
• Description: -
• mkdir() attempts to create a directory
named pathname.
• The parameter mode specifies the permissions
to use. It is modified by the process’s umask in
the usual way: the permissions of the created
directory are (mode & ~umask & 0777). Other
mode bits of the created directory depend on
the operating system.
• Return Value: - mkdir() returns zero on
success, or -1 if an error occurred (in which
case, errno is set appropriately).
• rmdir(): - rmdir() function is useful to delete
the directories.
• Syntax: -
#include <unistd.h>
int rmdir(const char *pathname);
• Description: - rmdir() deletes a directory,
which must be empty.
• Syntax: -
#include<sys/types.h>
#inlcude<sys/stat.h>
mode_t umask(mode_t new_umask);
• The new_umask argument is specified as the
bitwise ‘OR’ of any of the file access
permission constants such as S_IRUSR,
S_IWUSR, S_IXUSR etc;
• seekdir(): - set position of directory stream
• Syntax: -
#include <sys/types.h>
#include <dirent.h>
void seekdir(DIR *dirp, long int loc);
• Description: -
• The seekdir() function sets the position of the
next readdir() operation on the directory
stream specified by dirp to the position
specified by loc. The value of loc should have
been returned from an earlier call to telldir().
The new position reverts to the one
associated with the directory stream
when telldir() was performed.
• If the value of loc was not obtained from an
earlier call to telldir() or if a call
to rewinddir() occurred between the call
to telldir() and the call to seekdir(), the results
of subsequent calls toreaddir() are
unspecified.
• Return Value: -
The seekdir() function returns no value.
• telldir(): - current location of a named
directory stream
• Syntax: -
#include <dirent.h>
long int telldir(DIR *dirp);
• Description: -
• The telldir() function obtains the current location
associated with the directory stream specified
by dirp. If the most recent operation on the
directory stream was a seekdir(), the directory
position returned from the telldir() is the same as
that supplied as a loc argument for seekdir().
• Return Value: -
Upon successful completion, telldir() returns the
current location of the specified directory stream
fork Function
• An existing process can create a new one by
calling the fork function.
• The new process created by fork is called
the child process.
Example:-
• $pwd
Syntax:-
• $ls [options] [path]
Example:-
• $ls
Syntax:-
• mkdir [options . . . ] [directories . . .]
Example:
• $rmdir created
Example:
• echo class7 | sed 's/class/jtp/'
• echo class7 | sed 's/7/10/'
• cat msg.txt | sed 's/learn/study/'
Global Replacement
• To edit every word we have to use
a global replacement 'g'. It will edit all the
specified word in a file or string.
Syntax:
• command | sed 's/<oldWord>/<newWord>/
Example:
• echo class7 class9 | sed 's/class/jtp/g'
• cat msg.txt | sed 's/learn/study/g'
Removing a Line:-
• The 'd' option will let you to remove a
complete line from a file.
• You only need to specify a word from that line
with 'd' option and that line will be deleted.
• But please note that all the lines having that
same word will be deleted.
Syntax:
• cat <fileName> | sed '/<Word>/d'
Example:
• cat msg.txt | sed '/jtp/d'
3. DISPLAY FILE (more)
• As 'cat' command displays the file content.
Same way 'more' command also displays the
content of a file.
• Only difference is that, in case of larger files,
'cat' command output will scroll off your
screen while 'more' command displays output
one screen ful at a time.
Syntax: more <file name>
Example: more /var/log/udev
Options
Option Explanation
-c Clears screen before displaying
-d Displays error messages
-f Does not screen wrap long lines.
-l Ignores form feed characters.
-r Displays control characters in format ^C
-s Squeezes multiple blank lines (leaving only one blank line in output)
-u Suppresses text underlining
-w Waits at end of output for user to enter any key to continue
-lines Sets the number of lines in a screen (default is screen size -2)
+nmbr Starts output at the indicated line number (nmbr)
+/ptrn Locates first occurrence of pattern (ptrn) and starts output two lines
before it.
• If there is more than one screen of data, more
displays one screen, less two lines.
Syntax:-
• cp <existing file name> <new file name>
cp command Option
• The copy command has three options:
preserve attributes (-p)
interactive (-i)
recursion (-r)
• Preserve Attributes Option:-
When the destination file exists, its
permissions, owner and group are used rather
than the source file attributes.
• We can force the permissions, owner and
group to be changed, however by using the
preserve (-p) option.
Example:-
• $ cp –p file1 file2
• Interactive Option:-
We can guard against a file being accidentally
deleted by a copy command by using the
interactive (-i) option.
• When the interactive option is specified, copy
asks if we want to delete an existing file.
• If we reply y or yes, the file is replaced. If we
reply n or no, the copy is cancelled.
Example:-
• $cp –i file1 file2
Recursive copy:-
• Another way we can copy a collection of files
is with the recursive (-r) copy.
• The recursive copy copies the whole directory
and all of its subdirectories to a new directory.
Example:-
• $cp –r DirA DirB
2. MOVE (mv) Command
• The move (mv) command is used to move
either an individual file, a list of files, or a
directory.
Syntax:-
• ln [options] source destination
Example:-
• $ln file1 file2
ln Options
• Link has three options:
Symbolic.
Interactive.
Force.
Example:-
• $ln –f file2 1nDir
5. Remove (rm) Command
• rm stands for remove.
• rm [OPTION]... FILE...
rm Options
1. -i (Interactive Deletion):-
Example:-
$rm –f e.txt
3. -r (Recursive Deletion):-
• With -r(or -R) option rm command performs
a tree-walk and will delete all the files and
sub-directories recursively of the parent
directory.
Example:-
Example:- $groups
Security Levels
• There are three levels of security in UNIX:
System.
Directory.
File.
• The system security is controlled by the
system administrator, a super user.
2. Write permission.
3. Execute permission.
File Level Permission
1. Read permission.
2. Write Permission.
3. Execute Permission.
Checking Permission
• To check the permissions of a file or directory,
we use the long list command (ls -l).
Changing Permission (chmod)
• When a directory or a file is created, the
system automatically assigns default
permissions.
Example:-
$umask
000
$umask 022
$umask
022
Changing Ownership and Group
• Every directory and file has an owner and a
group. When you create a directory or file,
you are the owner and your group is the
group.
Options:-
• Syntax:-
Example:-
$chgrp proj15 file2
DISK UTILITIES
1. df
2. du
3. mount
4. umount
df
• The df command, stands for Disk Free, reports
file system disk space usage.
$df -h
3. Display disk space usage only in MB
To view file system disk space usage only in
Megabytes, use -m flag.
Syntax:-
$ df -m
4. List inode information instead of block
usage
We can list inode information instead of
block usage by using -i flag.
Syntax:-
$ df -i
5. Display the file system type
To display the file system type, use -T flag.
Syntax:-
$ df -T
6. Display only the specific file system type
We can limit the listing to a certain file
systems. for example ext4. To do so, we use -
t flag.
Syntax:-
$ df -t ext4
7. Exclude specific file system type
Some times, you may want to exclude a
specific file system from the result. This can
be achieved by using -x flag.
Syntax:-
$ df -x ext4
8. Display usage for a folder
To display the disk space available and where
it is mounted for a folder, for
example /home/sk/, use this command:
Syntax:-
$ df -hT /home/sk/
du
• du command, short for disk usage, is used to
estimate file space usage.
Syntax:
• head <file name> <file name>
Example:
• head doc1.txt doc2.txt
Options:-
1. -n:- The 'head -n' option displays specified
number of lines.
Syntax:
• head -n <file name>
Example:
• head -15 jtp.txt
tail Command
• The tail command also outputs data, only this
time from the end of the file.
Syntax:-
• tail [options] filename
Example:-
• $tail hai.txt
• It has several options. If the option starts with
a plus sign, tail skips N-1 lines before it begins
to output lines from the file and continues
until it gets to the end of the file.
• Syntax:-
cut OPTION... [FILE]...
• Since cut looks for columns, we must have
some way to specify where the columns are
located.
Example:-
• $cut –f1 filename
• Note:- The cut command is similar to the head
and tail commands. The cut command cuts
files vertically (columns), whereas the head
and tail commands cut files horizontally
(lines).
paste Command
• Paste command is one of the useful
commands in Unix or Linux operating system.
• Example:
• Options with sort function
-o Option :
Unix also provides us with special facilities like
if you want to write the output to a new file,
output.txt, redirects the output like this or you
can also use the built-in sort option -o, which
allows you to specify an output file.
• -r Option: Sorting In Reverse Order : You can
perform a reverse-order sort using the -r flag.
the -r flag is an option of the sort command
which sorts the input file in reverse order i.e.
descending order by default.
• -n Option : To sort a file numerically used –n
option. -n option is also predefined in Unix as
the above options are. This option is used to
sort the file with numeric data present inside.
• -nr option : To sort a file with numeric data in
reverse order we can use the combination of
two options as stated below.
• -k Option : Unix provides the feature of
sorting a table on the basis of any column
number by using –k option.
• -u option : To sort and remove
duplicates pass the -u option to sort. This will
write a sorted list to standard output and
remove duplicates.
• Syntax:-
1. How to convert lower case to upper case
To convert from lower case to upper case the
predefined sets in tr can be used.
2. How to translate white-space to tabs
The following command will translate all the
white-space to tabs.
3. How to translate braces into parenthesis
You can also translate from and to a file. In
this example we will translate braces in a file
with parenthesis.
4. How to use squeeze repetition of
characters using -s
To squeeze repeat occurrences of characters
specified in a set use the -s option.
• wc [OPTION]... [FILE]...
Example
• $cmp file1.txt file2.txt
Options:-
1. -b(print-bytes) : If you want cmp displays
the differing bytes in the output when used
with -b option.
• The values 154 and 151 in the above output
are the values for these bytes, respectively.
2. -l option : This option makes the cmp
command print byte position and byte value
for all differing bytes.
3. -s option : This allows you to suppress the
output normally produced by cmp
command i.e it compares two files without
writing any messages. This gives an exit value
of 0 if the files are identical, a value of 1 if
different, or a value of 2 if an error message
occurs.
diff command
• diff stands for difference. This command is
used to display the differences in the files by
comparing the files line by line.
Syntax :
Syntax
• nl [OPTION]... [FILE]...
w command
• w command in Linux is used to show who is
logged on and what they are doing.
• Syntax
unlink FILE
unlink OPTION
Options
• --help
Display a help message and exit.
• --version
Output version information and exit.
Examples
• unlink hope.txt
Options
• -c option: Displaying the count of number of
matches. We can find the number of lines that
match the given string.
Example:
• $fgrep -c "usin.g" para
• -h option: To display the matched lines.
Example:
• fgrep -h "usin.g" para
• -i option: Used in case insensitive search. It
ignore upper/lower case distinction during
comparisons. It matches words like :
“geeks*forgeeks”, “Geeks*forgeeks”.
Example:
• fgrep -i "geeks*forgeeks" para
• -n option: Precede each line by its line
number in the file. It shows line number of file
with the line matched.
Example:
• $ fgrep -n "learni\ng" para
Department of Information technology 719
BACK UP UTILITIES
1. tar
2. gzip
3. cpio
1. tar
• The primary function of the UNIX tar
command is to create backups.
Syntax:
Syntax:
Syntax:
• $ x=UNIX
$ y=$x
$ echo $y
Output : UNIX.
• For removing variables which we are defined
syntax is
• $ unset variablename
• Predefined variables:
• Predefined variables are used to configure a
user’s shell environment.
• $ echo $1
Output: Thu
• $ shift 1 // this command is used for shifting to next field
$ echo $1
Output: Sep
• $x=3 y=5
• $expr 3 + 5
• output: 8
• $expr $x + $y
• output: 8
• $x=`expr $x + 1`
• $echo $x
• output: 4
The Environment
• An important UNIX concept is the
environment, which is defined by
environment variables.
if command is successful
then
Command
fi
if-else
• if-else executes an action if the exit status of its
test command is true; if false, then
the else action is executed.
• Syntax :
if command is successful
then
command
else
command
fi
elif
• elif allows you to nest if structures, enabling
selection among several alternatives; at the
first true if structure, its commands are
executed and control leaves the
entire elif structure.
• Syntax:
if command is successful
then
command
elif command is successful
then
command
else
command
fi
• Using test or [ ] to Evaluate Expressions:
• The if conditional can’t handle relational tests
directly, but only with assistance of
the test statement.
• test uses certain operators to evaluate the
condition on its right and returns an exit
status, which is used by if for making
decisions.
• test works in 3 ways:
• Compares two numbers (like test $x –gt $y or [
$x –gt $y ]).
• Compares two strings or a single one for a null
value (like test $x = $y).
• Checks a file’s attributes (like test –f $file).
• Numerical comparison operators used
with test:
• Operator Meaning
• -eq Equal to
• -ne Not equal to
• -gt Greater than
• -ge Greater than or equal to
• -lt Less than
• -le Less than or equal to
• String tests with 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 null
• s1 == s2 String s1 = s2 (Korn and Bash
only)
• File Attribute Testing with test:
if [ -e file ]
then
echo “File exists”
fi
case
• case matches the string value to any of several
patterns. If a pattern is matched, its
associated commands are executed.
• Syntax: -
• case expression in
pattern 1) command 1;;
pattern 2) command 2;;
*) command;;
esac
echo -e “Menu \n 1. List of files \n 2. Todays Date
\n 3. Users \n 4. Exit \n
Enter your choice: ”
read choice
case $ choice in
1) ls;;
2) date;;
3) who;;
4) exit;;
*) echo “Invalid Option”
esac
Loop Control Structures
• while,
• For
• until
While
• while executes an action as long as its test
command is true.
Syntax:
Output: 1 2 3
Until
• until executes an action as long as its test
command is false.
Syntax:
until command
do
command
done
• Eg:
until [ $x -eq $y ]
do
echo $x
done
• break: break is designed for breaking the looping
statements
• Eg:
for i in 1 2 3 4 5
do
if [ $ i -eq 3 ];
then
break;
fi
echo $i
done
Output: 1 2
• continue: continue is designed to continue the
loop at specific condition
Eg:
for i in 1 2 3 4 5
do
if [ $ i – eq 3 ];
then
continue;
fi
echo $i
done
Output: 1 2 4 5
Shell Script Example
echo PROGRAM TO FIND BIGGEST OF 3
NUMBERS
echo Enter 3 numbers
read a
read b
read c
if [ $a -ge $b ] && [ $a -ge $c ]
then
echo $a is big
elif [ $b -ge $c ]
then
echo $b is big
else
echo $c is big
fi