Unix Basic Material
Unix Basic Material
INDEX
SL.NO. CONTENTS PAGE NO.
01 INTRODUCTION 2-2
02 UNIX ARCHITECTURE 3-4
03 THE UNIX FILESYSTEM 5-6
ies
04 BASIC COMMANDS 6 - 17
05 LINK FILES 17 - 18
06 WHAT IS A PATH 18 - 20
og
07 FILE PERMISSIONS 20 - 25
08 Vi EDITOR 25 - 28
ol
09 FIND FILES 29 - 33
10 AWK 34 - 37
hn
11 SED (STREAM EDITOR) 37 - 39
12 COMMUNICATION COMMANDS 39 - 43
13 PROCESS MANAGEMENT c 43 - 52
Te
14 SHELL SCRIPTING 53 - 53
15 SHELL SUPPORT FEATURES 54 - 57
ai
16 TYPE OF OPERATORS 57 - 61
17 CONTROL STATEMENTS 61 - 71
eS
18 POSITIONAL PARAMETERS 72 - 72
19 FILE TEST 72 - 73
re
20 MISCELLANEOUS 73 - 73
Sh
INTRODUCTION
What is UNIX?
The UNIX operating system is a set of programs that act as a link between the computer and the user.
The computer programs that allocate the system resources and coordinate all the details of the computer's
internals is called the operating system or kernel.
ies
Users communicate with the kernel through a program known as the shell. The shell is a command line
interpreter; it translates commands entered by the user and converts them into a language that is
og
understood by the kernel.
Unix was originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken
ol
Thompson, Dennis Ritchie, Douglas McIlroy, and Joe Ossanna.
hn
There are various Unix variants available in the market. Solaris Unix, AIX, HP Unix and BSD are few
examples. Linux is also a flavor of Unix which is freely available.
c
Several people can use a UNIX computer at the same time; hence UNIX is called a multiuser system.
Te
A user can also run multiple programs at the same time; hence UNIX is called multitasking.
ai
HISTORY OF UNIX:-0020
eS
Before development of Unix operating system at AT & T Bell Labs, Software team lead by ken
Thomson Dennis Ritchie and Rudd Candy worked on MULTICS project . MULTICS stands for Multi
Information Computing System. The aim of this project is to share the same data by ‘n’ number of
re
users at the same time. Initially, MULTICS was developed for only two users .Based on the same
concept in 1969,UNICS operating system was developed for 100’s of users.UNICS stands for uniplexed
Sh
information Computing System. Initially UNICS was written Assembly Language in 1973 they written in
‘c’ Language named as UNIX
UNIX ARCHITECTURE
Usr
Shell
Kernal
ies
HW
og
ol
c hn
Te
KERNEL
ai
Kernel is used in UNIX like systems and is considered to be the heart of the operating system. It is
responsible for communication between hardware and software components. It is primarily used for
eS
Kernel Activities:
re
Managing the computer resources: Kernel allows the other programs to run and use the resources.
Resources include i/o devices, CPU, memory.
Kernel is responsible for Process management. It allows multiple processes to run simultaneously
SHELL
Linux shell is the user interface to communicate with Linux operating system. Shell is a command checker
.It’s origin of “c” Language. Shell interprets the user requests, executes them. Shell may use kernel to
execute certain programs. Shell Script: A shell script is a program file in which certain Linux commands are
placed to execute one after another. A shell script is a flat text file. Shell scripts are useful to accept inputs
ies
and provide output to the user. Everyday automation process can be simplified by a shell script.
og
The Unix file system called as hierarchical file system. In fact, within the Unix system, There is no limit to
the number of files and directories you can create in a directory that you own. File systems of this type are
ol
often called tree-structured file systems, because each directory allow you to branch off into other
directories and files . The Unix file system resembles an upside down tree.
c hn
Te
ai
eS
re
Sh
All data in UNIX is organized into files. All files are organized into directories. These directories are
organized into a tree-like structure called the filesystem.
When you work with UNIX, one way or another you spend most of your time working with files. This
tutorial would teach you how to create and remove files, copy and rename them, create links to them
ies
etc.
og
Ordinary Files: An ordinary file is a file on the system that contains data, text, or program instructions.
In this tutorial, you look at working with ordinary files.
ol
Directories: Directories store both special and ordinary files. For users familiar with Windows or Mac
hn
OS, UNIX directories are equivalent to folders.
Special Files: Some special files provide access to hardware such as hard drives, CD-ROM drives,
c
modems, and Ethernet adapters. Other special files are similar to aliases or shortcuts and enable you to
Te
access a single file using different names.
ai
/root: This is root directory of the file system, the main directory of the entire file system, and the
eS
/bin: bin stands for binary. This directory contains executable files for most of the Unix
re
/sbin: This directory contains all system admin executable files (or) commands. This contains
programs used in booting the system and in system recovery.
/etc :- This directory contains all system configuration files and the files which maintain
information about users and groups. Ex. Group Name, G.I.D, User Name, U.I.D.
/usr:- This is user name directory. Default directory provided by unix O.S. to create users home
directories and contains manual pages.
/tmp:- This directory contains all temporary files used by the Unix system. System on users
creates temporary files which will be removed when the server reboots.
/dev:- This directory contains all logical device files it maintains device for information’s directory.
Ex. All disks devices are in the subdirectory /dev/dsk.
/home: - Default directory allocated for the home directory of normal users when the administrator
don’t specify any other directory. If your log name is root (or) sai, your default home directory is
ies
/home/root (or) sai.
og
/lib:- This directory contains all the library functions. Provided by UNIX programmers.
ol
/kernel This directory contains platform independent loadable kernel modules required as part of the
boot process.
hn
/mnt:- It contains entries for removable (mountable) media such as cd-roms and DLT Tapes.
c
Te
Basic Commands:-
# Pwd : It display the present (current) working directory ex: PWD ┘
ai
# Date : It displays the current system date & time. Mon Mar 12 010:10:10 IST 2009
Sh
# who : It display the list of users who are currently logged in to the server.
ie. Each user logname, terminal No, date & time that the person logged in
# finger : It displays complete information about all the users who are logged in to the users who
# whoami : It displays current username, terminal no, data $ time at which you logged in the
system.
# Cal : It displays the previous month, current month and next month calendar.
# Cal year : It display the given year calendar cal 2009 it takes year from 1 to 9999
# Cal month year : It display the given month, year cal only
ies
Ex: where is pwd ┘
og
ex: banner sai ┘
ol
# init Ө : To shut down the system (ok boot prompt)
hn
# init 1 : To bring the system to single user mode.
c
Te
# init 2 : To bring the system to multi user mode with
# init 3 : To bring the system multi user mode but CLI mode with source shared. (with sharing)
multi user
eS
Touch : It creates zero byte file size touch does allow you to store anything in a file. It is used for
Ex : touch 1 2 3 4 5
Cat : It is used for create a new file (or) to open a exiting file (or) to append the data to the file
ies
Ex : # cat > file name
og
------------------ >“ “ output
ol
To open the file :
hn
Ex : # cat > file name
(or) c
Te
Cat filename
ai
-------
re
-------
Sh
Control + d
Ex : # cat 1 2 3 4
# cat 1 2 > 3
Options :
-v → Display non-printing characters, except tabs, new – lines and form – feeds
-e → display $ at the end of each line (prior to new – line) (when used with –v option)
Removing Files :
ies
Sy:- # rm file name
Options :
og
-i : it asks confirmation before deleting the file
ol
Sy : # rm –i file name
hn
Remove file name? y – It removes
N – It won’t remove
c
Te
To remove the multiple files:
Creating Directory:
re
ex : mkdir /sai
Sh
Options :-
# mkdir -p /a1/a2/a3
Change Directory :
LINUX BASICS MATERIAL 9 www.shreesaitechnologies.com
040-23752633 LINUX BASICS MATERIAL
# cd /sai
# pwd
- /sai
ies
# cd…. to change in to parent directory
og
Remove Directory: - A Directory need to be empty before you can remove it. If it’s not, you need to
remove the files first also. You can’t remove a directory if it is your present working directory. You must first
ol
change out of it.
hn
Syntax : - # rm dir /dir name to delete a directory but directory should be empty.
Options:-
c
Te
-r → it removes all files and sub directories, sub directory files including directory.
ai
Options :-
Sh
-f → don’t prompt, even when copying over an existing target file (overrides – i)
Options:-
# cp 1 2
# cp -i 2
Overwrite 2 ?
This the most widely used command in Unix or Linux. “ls” command is used to list the contents of a
directory. Learn the power of ls command to make your life easy. The syntax of ls command is
ies
ls [options] [pathnames]
og
To display the hidden files and directories in the current directory use the -a option of the ls command.
ol
hn
# ls -a
. .. documents .hidden_file sum.pl
c
Te
Hidden files are the one whose name starts with dot (.). The ls -a displays the current directory (.) and
parent directory (..) also. If you want to exclude the current directory, parent directory, then use -A option.
ai
# ls -A
eS
# ls -F
documents/ sum.pl link@
The -1 option to the ls command specifies that each file should be displayed on a separate line
# ls
documents
sum.pl
ies
In some cases, you want to know the inode number of a file. Use -i option to the ls command to print the
og
inode number of a file.
ol
# ls -i
hn
10584066 documents
3482450 sum.pl
c
Te
The -l option provides lots of information about the file type, owner, group, permissions, file size, last
modification date.
ai
eS
# ls –l1
total 16
re
The first character indicates the type of the file. - for normal file, d for directory, l for link file and s
for socket file
The next 9 characters in the first field represent the permissions. Each 3 characters refers the read
(r), write (w), execute (x) permissions on owner, group and others. - means no permission.
The sixth field represents the last modification date and time of the file.
The -t option allows the ls command to sort the files in descending order based on the modification time.
ies
# ls -t1
sum.pl
documents
og
The -r option reverses the order of the files displayed. Combine the -t and -r options to sort the files in
ol
ascending order.
hn
# ls -rt1
documents
c
Te
sum.pl
So far the ls command prints the files in the current directory. Use the -R option to recursively print the files
ai
# ls -R
.:
Sh
documents sum.pl
./documents:
file.txt
You can pass a directory to the ls command as an argument to print for the files in it.
# ls /usr/local/bin
# ls -x
ies
Prefix Description
og
- Regular file, such as an ASCII text file, binary executable or hard link.
ol
B Block special file. Block input/output device file such as a physical hard drive.
hn
C Character special file. Raw input/output device file such as a physical hard drive
L c
Symbolic link file. Links on any regular file.
Te
P Named pipe. A mechanism for interprocess communications
ai
File type Permission Link Username Group Size of bytes Date Filename
* ? [] -
COMMANDS DESCRIPTION
ending letter is k.
ies
ls a?k It displays all three length files names but starting
letter is a..
og
ls b??k It displays all 4 length filenames but starting letter
ol
ls [aeiou]* It displays all files whose first character is anything
hn
other than a vowel
c
and v
Te
ai
Examples:-
# cat > sample
re
ies
O|p: I wisdom is rputd word….
og
#tr –d “aeiou” < sample
ol
O|p: wzdm s rptd nsttt….
hn
It deletes lower case “aeiou” vowel characters from sample file
Cut: it is used for to extract specified fileds and characters from a given file….
eS
#cut -f 2, 3 stud
re
#cut -f 3- stud
It displays every line 1st character to 10th character from stud file.
ies
It displays every 5th character to 10th character and 15th charcter to 20th character from stud file.
og
LINK FILES:
ol
A link is not a kind of file but instead is a second name for a file. When a file had two links it is not
hn
physically present at two places, but can be referred to by either of the names. This is very useful future.If
you accidentally delete a file with a single link or a single name, there is no bringing it back, as Unix has?
c
links your file is safe even if one of the links sets several. A link is severed when the file is deleted.
Te
The concept of having several links to a file offer another advantage, if one file is to be shared b/n several
users; instead of giving each user a separable copy of the same file we LAN create links of this file in each
ai
user’s directory. This avoids unnecessary duplication of the same file contents in different directories.
eS
The above command establishes one more link for the file sample in the form of the name my sample
re
SYMBOLIC LINKS
Links can be used to assign more than one name to a file, but they have some important limitations. They
Sh
cannot be used to assign a directory more than one name. And they cannot be used to lik filenames on
different computers.
These limitations can be eliminated using symbolic links. A symbolic link is a file that only contains the
name of another file. Then the operating system operates on a symbolic links can assign more than one
name to a file, and they can assign more than one name to a directory.
The ln command can link files within a single file system. You can also link files across file systems using the
–s(symbolic) option to ln. The following example shows show you could use this feature to link a file in the
/var file system to an entry in one of your directories within the /home file system.
ln –s /var/x/docs/readme temp/x.readme
In addition to allowing links across file system, symbolic links enable you to link directories as well as
ies
regular files.
WHAT IS A PATH?
A path is a unique location to a file or a folder in a file system of an OS. A path to a file is a combination of
og
/ and alpha-numeric characters.
ol
WHAT IS AN ABSOLUTE PATH?
An absolute path is defined as the specifying the location of a file or directory from the root directory(/). In
hn
other words we can say absolute path is a complete path from start of actual filesystem from / directory.
/etc/samba.smb.conf
ai
/boot/grub/grub.conf
If you see all these paths started from / directory this is a root directory for every Linux/Unix machines.
eS
Relative path is defined as path related to the present working directory(pwd). Suppose I am located in
re
/var/log and I want to change directory to /var/log/kernel. I can use relative path concept to change
Sh
directory to kernel
pwd
/var/log
cd kernel
Note: If you observe there is no / before kernel which indicates it's a relative directory to present working
directory.
cd /var/log/kernel
Note: We can use an absolute path from any location where as if you want to use relative path we should
be present in a directory where we are going to specify relative to that present working directory.
Examples of relative path and absolute path for the same operation.
ies
Example1: Present location is /abc/xyz, I am want to remove /abc/xyz/read/hello.txt file.
og
rm read/hello.txt
ol
rm /abc/xyz/read/hello.txt
hn
Example2: My present location is /etc/samba and now I want to change directory to /etc.
c
Te
cd ..
cd /etc
eS
Example3: My present location is /var/ftp/ and I want to change the location to /var/log
cd ../log
cd /var/log
cd ../../opt/oradba
cd /opt/oradba
Example5: My present location is /usr/local and I want to remove a abc.txt file located in this directory how
can I do that?
rm abc.txt
ies
rm /usr/local/abc.txt
I hope this helps to understand the difference between Absolute and relative path.
og
FILE PERMISSIONS
ol
File ownership is an important component of UNIX that provides a secure method for storing files. Every
hn
file in UNIX has the following attributes:
Owner permissions: The owner's permissions determine what actions the owner of the file can perform on
the file. c
Te
Group permissions: The group's permissions determine what actions a user, who is a member of the group
that a file belongs to, can perform on the file.
ai
Other (world) permissions: The permissions for others indicate what action all other users can perform on
the file.
eS
$ls -l /home/pungki
-rwxr-xr-- 1 pungki users 1024 Nov 2 00:10 myfile
Sh
Here first column represents different access mode ie. permission associated with a file or directory.
The permissions are broken into groups of threes, and each position in the group denotes a specific
permission, in this order: read (r), write (w), execute (x):
The first three characters (2-4) represent the permissions for the file's owner. For example -rwxr-xr--
represents that onwer has read (r), write (w) and execute (x) permission.
The second group of three characters (5-7) consists of the permissions for the group to which the file
belongs. For example -rwxr-xr-- represents that group has read (r) and execute (x) permission but no write
permission.
The last group of three characters (8-10) represents the permissions for everyone else. For example -rwxr-
xr-- represents that other world has read (r) only permission.
1. Read:
ies
Grants the capability to read ie. view the contents of the file.
2. Write:
og
Grants the capability to modify, or remove the content of the file.
ol
3. Execute:
hn
User with execute permissions can run a file as a program.
c
Directory access modes are listed and organized in the same manner as any other file. There are a few
Te
differences that need to be mentioned:
ai
1. Read:
Access to a directory means that the user can read the contents. The user can look at the filenames inside
eS
the directory.
2. Write:
re
Access means that the user can add or delete files to the contents of the directory.
Sh
3. Execute:
Executing a directory doesn't really make a lot of sense so think of this as a traverse permission.
A user must have execute access to the bin directory in order to execute ls or cd command.
Changing Permissions:
To change file or directory permissions, you use the chmod (change mode) command. There are two ways
to use chmod: symbolic mode and absolute mode.
The easiest way for a beginner to modify file or directory permissions is to use the symbolic mode. With
symbolic permissions you can add, delete, or specify the permission set you want by using the operators in
the following table.
ies
Removes the designated permission(s) from a file or
-
og
directory.
ol
= Sets the designated permission(s).
hn
Here's an example using testfile. Running ls -1 on testfile shows that the file's permissions are as follows:
$ls -l testfile
c
Te
-rwxrwxr-- 1 pungki users 1024 Nov 2 00:10 testfile
Then each example chmod command from the preceding table is run on testfile, followed by ls -l so you
ai
The second way to modify permissions with the chmod command is to use a number to specify each set of
permissions for the file.
Each permission is assigned a value, as the following table shows, and the total of each set of permissions
provides a number for that set.
ies
0 No permission ---
og
1 Execute permission --x
ol
2 Write permission -w-
hn
3 Execute and write permission: 1 (execute) + 2 (write) = 3 -wx
Here's an example using testfile. Running ls -1 on testfile shows that the file's permissions are as follows:
Sh
$ls -l testfile
-rwxrwxr-- 1 pungki users 1024 Nov 2 00:10 testfile
Then each example chmod command from the preceding table is run on testfile, followed by ls -l so you
can see the permission changes:
$ls -l testfile
-rwxr---wx 1 pungki users 1024 Nov 2 00:10 testfile
$chmod 043 testfile
$ls -l testfile
----r---wx 1 pungki users 1024 Nov 2 00:10 testfile
ies
While creating an account on Unix, it assigns a owner ID and a group ID to each user. All the permissions
mentioned above are also assigned based on Owner and Groups.
og
Two commands are available to change the owner and the group of files:
ol
1. chown: The chown command stands for "change owner" and is used to change the owner of a file.
2. chgrp: The chgrp command stands for "change group" and is used to change the group of a file.
hn
Changing Ownership:
The chown command changes the ownership of a file. The basic syntax is as follows:
c
Te
$ chown user filelist
The value of user can be either the name of a user on the system or the user id (uid) of a user on the
ai
system.
eS
Following example:
$
Sh
The chrgp command changes the group ownership of a file. The basic syntax is as follows:
The value of group can be the name of a group on the system or the group ID (GID) of a group on the
system.
Following example:
Vi EDITOR
Compared to ed or ex and vi editor is head and shoulders above them in almost every way. It is a screen
ies
editor rather than a line editor; it shows you as much of the file as it can fit on the screen. Vi is case-
og
Mode of operations
ol
The vi program has three nodes of operation:
hn
1) command mode:
This is the default mode in this mode all the keys pressed by the user are interpreted to be editor
commands
c
Te
2) Insert mode
This mode permits insertion of new text, editing of existing text or replacement of existing text.
This mode permits us to give commands at the command line. The bottom line of the vi screen is
eS
called the command line. VI uses the command line to display messages and commands .All
commands entered in the ex command mode ared displayed in the command line. This mode is
so called because commands given in this mode are compatible with the commands of the ex
re
editor.
Sh
Command Function
A It places cursor at end of the current line
A It places cursor right side of the cursor position
I It places cursor at beginning of the current line
I It places cursor left side of the cursor position
O Enters text input mode by opening a new line immediately
below the current line
0 Enters text input mode by opening a new line immediately
To edit your text,you need to move the cursor to the point on the screen where you will begin the
ies
correction. This is easily done with four keys h,j,k and l.
og
I Move the cursor one character to the right
J Move the cursor down on line
ol
K Move the cursor up on line
hn
Positioning by character
c
Te
Command Function
H Moves the cursor one character to the left.
ai
Positioning by line
Command Function
J Moves the cursor down one line from it’s present
K Moves the cursor up one line from it’s present position in the
sample column
+ Moves the cursor down to the beginning of next line.
- Moves the cursor upto the beginning of previous line.
Enter Moves the cursor down to the beginning of the next line.
Positioning by word
Command Function
W Move the cursor to the right, to the first character of the next word
B Move the cursor back to the first character of the previous word.
E Move the cursor to the end of the current word.
ies
og
Positioning in the window
Command Function
ol
H Moves the cursor to the first line on the screen, or “Home”
M Moves the cursor to the middle line on the screen
hn
L Moves the cursor to the last line on the screen
c
Te
Commands for positioning in the file
ai
Scrolling
eS
Commands Function
Ctrl f Scrolls the screen forward a full window, revealing the window
re
Commands Function
X Deletes the character at current cursor position
X Deletes the character to the left of the cursor
Dw Deletes a word(or part of a word) from the cursor to the next
space or to the ext punctuation.
Dd Deletes the current line.
Nx,ndw,ndd Deletes n characters, n words or nlines.
D0 Deletes the current line from the cursor to the beginning of the
line.
D$ Deletes the current line from the cursor to the end of the line.
ies
Commands Function
Yw Yank word from cursor position
Yy Yanks line from cursor position
og
Y$ Yanks line from cursor position of line
Y0 Yanks line from cursor position to beginning of line
ol
P Pastes last yanked buffer
c hn
Te
Commands for quitting vi
ai
Command Function
Zz Writes the buffer to the file and quits vvi
eS
quits vi.
:q! Quits vi whether or not changes made to the buffer were written to a
Sh
file. Does not incorporate changes made to the buffer since the last
write(:w) command
:q Quits vi changes made to the buffer were written to a file
Set nu Setting line numbers for file
Set nonum Removing line numbers
FIND FILES
The find command help s you locate files in the file system. with the find commands you can search
through any part of the filesystem. Looking for all files with a particular name. It is extremely powerful, and
at times it can be a lifesaver , but it is also rather difficult to remember and to use.
An example of an common problem that find can help solve is locating a file that you have misplaced for
example, if you want to find a file called sai but you can’t remember where you put it , you can use find to
ies
search for it through all or part of your directory system.
The find command searches through the contents of one or more directories including all of their sub
og
directories. You have to tell find in which directory to start its search. To search through all your directories,
ol
find command can find files according to
hn
1) File names
c
Te
2) File types
3) Permissions
ai
4) Owners
eS
6) Size
Sh
Example3: find all the files whose name contains both capital letters and small letters in it.
find /home –iname test.txt
-iname option is used to mention ignore the case sensitivity of a file.
Search for files depending on their File types:
ies
Example5: Search for an mp3 files whose name is temp.mp3
find / -type f –name temp.mp3
Below are the file types supported by find command, to know more about file types in Linux/Unix please
og
have a look at our other post on File types.
Sl.no Symbol Type
ol
1 F Regular file
2 D Directory file
hn
3 B Block file
4 C Character file
5 P
c Pipe file
Te
6 L Symbolic link file
7 S Socket file.
ai
Example6:Search for a file name test.txt and its permissions are 775 in a given box
find / -perm 775 –name test.txt
re
Example7: How about searcing files with SUID bit set and file permissions are 755?
find / -perm 4755
Sh
Example8:How can i find SGID bit set files with 644 permissions?
find / -perm 2644
Example9: How can i find Sticky bit set files in my system with permissions 551?
find / -perm 1551
Example10:Search for all the files whose SUID bit is set
find / -perm /u=s
Example11: Search for all the files whose SGID bit is set
find / -perm /g+s
Note: We can use = or + interchangeably to check if a permissions is set or not as shown in above two
examples.
Example12: Search for all the files whose StickyBit is set
ies
Example15: Search for all the files with name test.txt and the owner of this file is Surendra
find / -user Surendra –name test.txt
Example16: find all the files whos name is test.txt and owned by a group called redcluster
og
find / -group redcluster –name test.txt
to know more about owners and groups you have to look at our previous post on chown command.
ol
SEARCH ACCORDING TO MODIFIED DATE AND TIME.
hn
What is ctime, atime, and mtime?
c
It is important to distinguish between a file or directory's change time (ctime), access time (atime), and
Te
modify time (mtime).
CTIME -- In UNIX, it is not possible to tell the actual creation time of a file. The ctime--change time--is the
ai
time when changes were made to the file or directory's inode (owner, permissions, etc.). The ctime is also
eS
updated when the contents of a file change. It is needed by the dump command to determine if the file
needs to be backed up. You can view the ctime with the ls -lc command.
re
ATIME -- The atime--access time--is the time when the data of a file was last accessed. Displaying the
contents of a file or executing a shell script will update a file's atime, for example. You can view
Sh
MTIME -- The mtime--modify time--is the time when the actual contents of a file was last modified. This is
the time displayed in a long directoring listing (ls -l).
Examples
$ cat file
file's atime is updated.
$ chmod g+w file
Below is the matrix which give you brief idea on how to search according to modified date,
ies
accessed date etc.
og
SL. NO -CTIME -MTIME -ATIME
+90 File status changed more Modified more than 90 Accessed more than 90
ol
then 90 days back days back days back
90 File status changed exactly Modified exactly 90 days Accessed exactly 90 days
hn
90 days back back back
-90 File status changed less Modified less than 90 days Accessed less than 90
than 90 days
c days back
Te
Example17: Search for a file: test.txt whose file status is changed more than 90 days back
find / -ctime +90 –name test.txt
Example18: Search for all the files which are modified exactly 90 days back
ai
find / -mtime 90
Example19: Search for all the files with name test.txt which is accessed less than 90 days
eS
Below is the matrix which gives you brief idea on how to search according to modified time, accessed time
Sh
in minutes etc.
ies
Example25: I have new file called test.txt which is just created, now I want to get all the files which are
created later this file creation.
find / -newer test.txt
og
ol
SEARCH FOR FILES/FOLDERS DEPENDING ON THE SIZE WITH –SIZE OPTION
c hn
Te
SL.NO +10 10 -10
c for bytes(8 bits) Search for files more Search for files Search for files less
than 10c size exactly 10b size than 10b size
ai
k for kilobytes Search for files more Search for files Search for files less
than 10k size exactly 10k size than 10k size
eS
M for Megabytes Search for files more Search for files Search for files less
than 10M size exactly 10M size than 10M size
re
G for Gigabytes Search for files more Search for files Search for files less
than 10G size exactly 10G size than 10G size
Sh
AWK
Awk is one of the most powerful tools in Unix used for processing the rows and columns in a file. Awk
supports most of the operators, conditional blocks, and loops available in C language.
ies
SYNTAX:-
awk options 'selection-criteria {action}' files(s)
og
awk '/abc/{print}' test
Prints lines containing abc
ol
awk '/^unix/{print}' test
hn
awk -F: '$3 /^0$/' /etc/passwd
NR - Record Number
re
FS - Fields Seperator
NF - Number of Fields
Sh
Rs - Record Seperator
awk '{ print "Record No", NR, "has", NF, "fields"}' emp.list
ies
awk '$3 == "director" || $3 == "manager" {print}' emp.list
og
awk -F: '($3 > 1 && $3 < 4 ) || ($3 >=7 && $3 <=10 )' /etc/passwd
ol
hn
POSITIONAL PARAMERS
A shell script uses special parameters like $1,S2 etc to represent command line arguments. But awk uses
c
the same parameters as field identifiers. To distinguish between shell parameter and field identifier quoting
Te
will be used for positional parameters.
ai
Matching Pattern
For matching regular expression with a field, awk uses ~ operator and !~ negates the match
re
CONTROL STATEMENTS
awk supports conditional structures (if) and loops (while and for).
if ( condition ) {
statements
}
else {
statements
awk -F: '{ if ( $3 > 100 ) { print $1,$3 } else { echo "Not Found" } }' /etc/passwd
while
-----
ies
while ( condition ) {
statements
og
}
ol
for
hn
----
}
ai
or
eS
statements
}
Sh
FUNCTIONS
awk has several built-in functions, performing both arithmetic and string operations.
ARITHMETIC
STRING
ies
awk -F: '{print length()}' /etc/passwd
og
From a file
ol
cat > emp.awk
hn
$3 == "director" && $6 > 12000 { printf "%4d %-20s %-12s %d\n", ++kount, $2,$3,$6}
Syntax
Sh
commands
d delete line(s)
ies
w file writes addressed lines to the file
og
s/s1/s2 Replaces first occurence of s1 in all lines with s2
ol
s/s1/s2/g Replaces all occurences
hn
Ex:-
---
c
Te
sed '1,4d' test Remove 1 & 4 lines from the file test
ai
sed '/begin/,/end/' test Print line containing begin throught line containing end
sed '1i\
>abc\
sed 'a\
ies
sed '/^#/d' test Delets comments
og
ol
COMMUNICATION COMMANDS
The write command:
hn
The write command can be used by any user to write something on someone else’s terminal,
Ctrl d
re
b) The recipient must have given permission for message to reach his or her terminal. This is done by
saying at the $prompt
$mesg -y
If you are expecting nothing of consequence and do not wish to be disturbed by social trivial like the one
we just saw. You can deny write permission to your terminal by saying
$mesg -n
A superuser however can write to any terminal, irrespective of whether mesg has been set –y or –n
Mail command:-
Using mail you can quickly and efficiently circulate memos and other written information to your co-
workers . You can even send and reeive mail from people outside your organization if you and they use
network computers. Mail can be sent to users who have logged in currently or even to users who haven’t
logged in currently in case the user has logged in at several terminals the moment mail is sent to this user
ies
it becomes available at all the terminals.
Sending mail:
og
$mail techno1
ol
Hello,
hn
How r u?
c
Shree sai technologies offering unix course with less fees.
Te
Ctrl + d
ai
To send the same mail to more than one user, you can say
eS
Hello,
Sh
Ctrl d
If you are to mail a program written by you and then you of course can not be expected to type in the
program after you have issued the mail. Commad as in the above case. In such cases . In such cases yu can
To read the mail that has been received we simply say mail at the shell prompt.
&
ies
The output shows that there are 3 messages in our mailbox of which I has been received since we logged
in whereas 2 were lying in the mail box unread even before we logged in. the N or a U in the first column
indicates just this.Each message present in the mail box is given a number. This members are shown in the
og
second column . The > sign indicates that the current message is message umber 3. Followd by this is the
logname of the person who sent the mail, the date and time when the mail was received as well as the
ol
subject of each message.
hn
Observe the & displayed at the bottom. This is known as the mail prompt. We can use several commands
at this prompt if you want to know which, you can type a / and obtain help on these commands. Let us
c
now view the seond message. Just type a 2 at the & prompt.
Te
&2
ai
&3
re
Finally, we exit from the mail command by typing q at the & prompt.
&q
This implies that out of the three messages we have recived we have hone through 2 messages hence they
have been removed from out primary mailbox file user/spool/mail/aa12 and appended to the secondary
mail box file/user/aa12/mbox. One message will remains unread is still lying in the primary mailbox file. If
we invoke mail once again we would be shown only the one unread message. What if we want to review
the message transferred to the secondary mailbox? Simply invoke the mail command as show below.
$mail –f
The following table shows the operations that you can perform on mail messages.
COMMAND ACTION
+ or return Print next message
- Print previous message
# Print number of urrent message
D Delete the message
ies
Dq Delete the message and quit
M person Mail this message to person(your own login name is
the default if person is not specified)
og
P Print current message again
Q or CTRL-D Put undeleted mail back in /var/mail/shree,and quit
ol
uN Undeleted message N
S file Save this message. $usr/mbox is used as a default if
hn
file is not specified.
W file Save the mail back .m mail file and quit
X
c Put all mail back in mail file and quit
Te
!command Escape to the shell and run command
? Print summary of mail command
Input/output redirections
ai
In all operating system, there is a standard input device and standard output device in unix, as also in most
eS
other operating systems, the standard input device is keyboard and the standard output is the display
screen
re
Special files that instruct all the programs to accept standard input from the keyboard and direct the
standard output to the display, are provided by Unix. The three streams, i.e. the standard input, standard
Sh
output and standard error are denoted by the numbers 0,1 and 2 respectively.
Sometimes it is useful to redirect the input or output to a file or a printer. For example, you might want to
redirect a directory listing from the screen to a file. Unix provides redirection symbols for the purpose.
The symbol “>” implies redirection of output and the symbol implies redirection of input.
The symbol”> “sends the output of a command to a file or a device, such as a printer.
The symbol”< “talks the input needed for a command from a file rather than from the keyboard.
The symbol”>>” adds output from a command to the end of a file without deleting the
ies
Piping :-
The unix piping facility let us connect commands to other commands. This facility is of utmost importance
in combining Unix commands and other operations. It can be really useful to redirect the output of one
og
program so that it becomes the input of another program, thereby joining of two programs. To send the
output of one command as input for another, the two commands must be joined using a pipe(|)
ol
characters.
hn
PROCESS MANAGEMENT
c
This is a very basic ps usage. Just type ps on your console to see its result.
Te
ai
eS
To do this, we can use -a options. As we can guess, -a is stand for “all”. While x will show all process even
the current process is not associated with any TTY (terminal)
$ ps -ax
This result might be long result. To make it more easier to read, combine it with less command.
$ ps -ax | less
ies
og
ol
c hn
Te
Filter processes by its user
ai
For some situation we may want to filter processes by user. To do this, we can use -u option. Let say we
want to see what processes which run by user Pungki. So the command will be like below
eS
$ ps -u Pungki
re
Sh
Another thing that you might want to see is filter the result by CPU or memory usage. With this, you can
grab information about which processes that consume your resource. To do this, we can use aux options.
Here’s an example of it :
$ ps -aux | less
ies
og
ol
hn
Since the result can be in a long list, we can pipe less command into ps command.
c
By default, the result will be in unsorted form. If we want to sort by particular column, we can add--
Te
sort option into ps command.
ies
og
Or we can combine itu a single command and display only the top ten of the result :
ol
$ ps -aux --sort -pcpu,+pmem | head -n 10
hn
To to this, we can use -C option followed by the keyword. Let say, we want to show processes named
getty. We can type :
c
Te
$ ps -C getty
ai
eS
re
If we want to show more detail about the result, we can add -f option to show it on full format listing. The
Sh
$ ps -f -C getty
If we need to know the thread of a particular process, we can use -L option followed by its Process ID (PID).
Here’s an example of -L option in action :
$ ps -L 1213
ies
og
ol
As we can see, the PID remain the same value, but the LWP which shows numbers of thread show different
values.
hn
Show processes in hierarchy
Sometime we want to see the processes in hierarchical form. To do this, we can use -axjfoptions.
c
Te
$ps -axjf
ai
eS
re
$ pstree
ies
og
ol
hn
Show security information
c
If we want to see who is currently logged on into your server, we can see it using the ps command. There
Te
are some options that we can use to fulfill our needs. Here’s some examples :
$ ps -eo pid,user,args
ai
Option -e will show you all processes while -o option will control the output. Pid, User and Args will show
eS
you the Process ID, the User who run the application and the running application.
re
Sh
The keyword / user-defined format that can be used with -e option are args, cmd, comm, command,
fname, ucmd, ucomm, lstart, bsdstart and start.
Show every process running as root (real & effecitve ID) in user format
System admin may want to see what processes are being run by root and other information related to it.
Using ps command, we can do by this simple command :
$ ps -U root -u root u
The -U parameter will select by real user ID (RUID). It selects the processes whose real user name or ID is in
the userlist list. The real User ID identifies the user who created the process.
The last u paramater, will display the output in user-oriented format which contains User, PID, %CPU,
%MEM, VSZ, RSS, TTY, STAT, START, TIME and COMMAND columns.
ies
Here’s the output of the above command.
og
ol
c hn
Te
ai
eS
ps will display a report of what happens in your system. The result will be a static report.
Let say, we want to filter processes by CPU and Memory usage as on the point 4 above. And we want the
Sh
report is updated every 1 second. We can do it by combining ps command with watch command on Linux.
ies
og
ol
c hn
Te
ai
If you feel the report is too long, we can limit it by - let say - the top 20 processes. We can
eS
ies
og
ol
c hn
Te
ai
This live reporter is not like top or htop of course. But the advantage of using ps to make live report is that
you can custom the field. You can choose which field you want to see.
eS
For example, if you need only the Pungki user shown, then you can change the command to become like
this :
re
ies
og
ol
c hn
Te
You may use ps on your daily usage to monitor about what happens your Linux system. But actually, you
ai
can generate various types of report using ps command with the use of appropriate paramaters.
Another ps advantage is that ps are installed by default in any kind of Linux. So you can just start to use it.
eS
re
Sh
SHELL SCRIPTING
SHELL
The shell read your commands and interprets them as requests to execute a program or programs, which
it then arranges to have carried out. It is called a command interpreter .Besides being a command
interpreter; the shell is also a programming language. as a programming language it permits you to
control how and when commands are carried out. Shell acts as an interface between user and the kernel.
ies
og
KERNEL
The kernel is the part of the operating system that interacts directly with the hardware of a computer,
ol
through device drivers that are built into the kernel. It provides set of services that can be used by
hn
programs; control these programs from the underlying hardware.
The major functions of the kernel are to manage computer memory, to control access to the computer, to
c
maintain file system, to handle interrupts (singles to terminate execution).
Te
To handle errors, to perform input and output services (which allow computers to interact with terminals,
ai
storage devices, and printers). And to allocate the resources of the computer (such as the cpu or
Programs interact with the kernel through approximately 100 system calls. System calls tell the kernel to
carry out various task for the program, such a s opening a file, writing to a file, obtaining information about
re
TYPES OF SHELLS
ies
Command history No Yes Yes Yes Yes
File completition No Yes Yes Yes Yes
Command line No Yes Yes Yes Yes
og
editing
Job control No Yes Yes Yes Yes
ol
hn
HIGHLIGHTS OF SHELL (korn, bash, cshell)
Use the tilde substitution feature to shorten pathnames that refer to the home directory,
Prevent accidental overwriting of files and login out using the set command.
eS
TYPE OF VARIABLES
Sh
ies
Rules for building shell variables (user defined variables)
og
The first character of variables name must either be alphabet or an underscore.
variable name is any combination of alphabets, digits and underscore(-)
ol
No commas or blanks are allowed within variable name.
Reserved words are not allowed
hn
Variable names are case sensitive, that is Name, NAME, name, Name are all different.
c
Te
Echo Until If Umask
Read Case Else Unlieval
Set Esac Fi Exec
ai
SHEBANG:
Sh
The #! Syntax used in scripts to indicate an interpreter for execution under Unix/Linux operating
systems . Most Linux shell and perl / python scripts start with the following lines
#! /bin/bash
Or
#! /usr/bin/perl
Or
#!/usr/bin/python
It consists of a number sign and an exclamation pointing character (#!), followed by the full path to the
interpreter such as /bin/bash.
All scripts under Linux execute using the interpreter specified on a first line.
Almost all bash scripts often begin with #!/bin/bash(assuming that bash has been installed in /bin)
This ensures that bash will be used to interpret the script, even if it is executed under another shell.
ies
The shebang was introduced b Dennis Ritchie between version 7 and Unix 8 at bell laboratories.
If you do not specify an interpreter line. The default is usually the /bin/sh .But it is recommended that you
set #!/bin/bash line.
og
COMMENT
ol
hn
You should be aware of the fact that you might not be the only person reading your code. A lot of users
and system administrators run scripts that were written by other people. If they want to see how you did it ,
comments are useful to enlighten the reader.
c
Te
Comments also make your own life easier. Say that you had to read a lot of man pages in order to achieve
ai
a particular result with some command that you used in your script. You won’t remember how it worked if
you need to change your script after a few weeks or months, unless you have commented what you did,
eS
By default shell script can be commented out prefixing # character, so if there are any lines starting with #
then those lines will be treated as comments and those will be removed at the time of executing the
Sh
scripts.
The easiest way to run shell script in linux or unix is to type the following commands. Open the terminal
and type the command.
$ sh myscript.sh
Or
$ bash myscript.sh
Another recommend option is to set an executable permission using the chmod a command as follows.
$ chmod +x myscript.sh
And run your shell script files as follows or you can give the full path of the file also.
$ ./myscript.sh
ies
Echo command:
The built-in echo command is an older form of printf command. Bash provides it for compatibility with
og
almost all the shells. Echo does not use a format string like printf command.
ol
It used to display the text or variables on the output screen. The following the examples narrates the usage
hn
of echo command
c
Te
TYPE OF OPERATORS
Arithmetic operator
ai
Relational operator
o Numeric comparison operator
eS
Arithmetic operations
Operator Meaning
Sh
+ Addition
- Subtraction
\* Multiplication
/ Division
% Modular division
NUMERIC COMPARISON OPERATOR
Operator Meaning
-gt Greater than
-ge Greater than or equal to
-lt Less than
ies
STRING COMPARISION OPERATOR COMPARISION
Condition Meaning
Str1=str2 True if the strings are same
og
Str1!=str2 True if the strings are different
-n string True if the length of string greater than zero
ol
-z string True if the length of string is zero
LOGICAL OPERATORS
hn
Operator Meaning
-a
c And
Te
-o Or
! Not
ai
1. Customizing your work environments. For example, every time you log in if you want to see the
current date, a welcome message and the list of users who have logged in you can write a shell
re
4. ESCAPE SEQUENCE
ies
\r carriage return
\ Double quotes
\’ Single quotes
og
\\ Back slash
\$ Dollar
ol
Shell variables:
hn
Variable is a data name and it is used to store value. Variable value can change during execution
of the program.
c
Te
Echo
Echo command is used to display the messages on the screen and is used to display the value
ai
Smmit Networks
Sh
SHELL VARIABLE
Eg 1: $a=10
Note: there are no predefined data types in Unix. Each and every thing it treat as character. Each
character occupies 1 byte of memory.
Eg 2:$b=2000
Reading of variables
ies
Eg 1:$n=100
og
$echo $n
ol
100
hn
Eg 2:$name =”smmit networks”
c
Te
Smmit networks
ai
NULL VARIABLE
eS
A variable which has been defined but has not been given any value is known as null variable, a
null variable can be created in any of the following ways.
re
1 $n=””
Sh
2 $n=’’
3 $n=
$echo n
$a=20
$read only a
When the variables are made read only, the shell does not allow us to change their values. So a
Note: If we want the shell to forget about a variable altogether, we use the unset command.
$unset a
ies
On issuing the above command the variable and with it the value assigned to it is erased from the shell’s
memory.
Expr: expr is the command to evaluating arithmetic expressions. But expr is capable of carrying out only
og
integer arithmetic.
ol
CONTROL STATEMENTS
hn
There are four types of control instructions in shell. They are:
The sequence control instruction ensures that the instructions are executed in the same order in which
they appear in the program. Decision and case control instructions allow the computer to take a decision
re
as to which instruction is to be executed next. The loop control instruction helps computer to execute a
Ls –a
Pwd
clear
Write a program to read 2 numbers and display sum, difference, product and division.
Read a b
C=`expr $a + $b`
Echo “a+b=$c”
ies
C=`expr $a - $b`
Echo “a-b=$c”
og
C=`expr $a \* $b`
ol
Echo “a*b=$a”
hn
C=`expr $a / $b`
Echo “a/b=$c”
c
Te
DECISION CONTROL STATEMENT.
If – then – fi statement
ai
Syntax
eS
If control command
re
-----------------------
----------------------
Sh
fi
The if statement of unix is concerned with the exit status of a command . The exit status indicates whether
the command was executed successfully or not. The exit status of a command is 0 if it has been executed
successfully, 1 otherwise.
Read dname
If cd $dname
Then
ies
Echo “changed to $dname”
Pwd
og
fi
ol
if else
hn
Syntax
If condition
c
Te
Then
-------
ai
-------
eS
Else
re
-------
-------
Sh
Fi
The exit status of the control command is 0 then it executes then statements otherwise it executes else
statements.
If cp $src $ trg
Then
ies
Else
og
Fi
ol
Write a program to check given no is even or odd
hn
Echo enter a number
Read n
c
Te
If [ `expr $n % 2` -eq 0 ]
Then
ai
Else
re
Fi
Sh
If constructs depends upon whether or not the condition results into true or not.
The test command helps us to find the contents of a variable, the number of variables and the type of file
or kind of file permission. The test command returns an exit status after evaluating the condition.
Syntax
If test condition
LINUX BASICS MATERIAL 64 www.shreesaitechnologies.com
040-23752633 LINUX BASICS MATERIAL
Then
Commands
Else
Commands
ies
Fi
og
Echo “enter first string:”
ol
Read str1
hn
Echo” enter second strings:”
Read str2
c
Te
If [ $str1 = $str2 ]
Then
ai
Else
re
Fi
Sh
Syntax
Case value in
Choice1)
---------
--------
;;
Choice2)
--------
-------
ies
;;
Choice 3)
og
---------
ol
---------
hn
;;
Choice n)
c
Te
---------
---------
ai
;;
eS
*)
re
---------
---------
Sh
;;
Esac
Firstly, the expression following the case keyword is evaluated. The value that it yields is then matched, one
by one against the potential choices(choice1,choice2,choice3 in the above from ).When a match is found,
the shell executes all commands in that case up to ;; this pair of semicolons placed at the end of each
choice as necessary.
Read num
Case $num in
ies
;;
og
;;
ol
3) Echo “ you entered 3”
;;
hn
4) Echo “ you entered 4”
;; c
Te
*) echo “ invalid number enter number between 1 to 4”
ai
;;
eS
Esac
A loop involves repeating some portion of the program either a specified number of times of times or until
Sh
a particular condition is being satisfies there are there methods by way of which we can retreat a part of a
1) While statement
Syntax
While [condition]
Do
--------------
--------------
--------------
Done
ies
The statement with in the while loop would keep on getting executed till the condition is true.
When the condition is false, the control transfers to after done statement.
og
Write a program display numbers 1 to 10
ol
hn
Echo “the number from 1 to 10 is:”
I=10;
c
Te
While [ $i –le 10 ]
Do
ai
Echo $i
eS
I=`expr $i + 1`
re
Done
Sh
When the keyword break is encountered inside any loop, control automatically passes to the first
When the keyword continues is encountered inside any loop, control automatically passes to the
X=0
ies
While test $x=0
Do
og
Echo “enter a file name: \c”
Read fname
ol
If test! –f $fname
hn
Then
Else break
eS
Fi
Done
re
Syntax
Until [condition]
Do
-----------
--------
--------
LINUX BASICS MATERIAL 69 www.shreesaitechnologies.com
040-23752633 LINUX BASICS MATERIAL
Done
The statements within the until loop keep on getting executed till the condition is false .when the condition
ies
I=1
Until [ $i –gt 10 ]
og
Do
Echo $i
ol
I=`expr $i + 1`
hn
Done
Syntax
Do
Sh
----------------------
---------------------
---------------------
Done
The for allows us to specify a list of values which the variable in the loop can take. The loop is then
For I In 1 2 3 4 5
Do
Echo $i
Done
ies
Write a program to display all sub-directories in the current directory
For I in *
og
Do
ol
If [ -d $i ]
Then
hn
Echo $i
Fi
c
Te
Done
Positional parameters
When the arguments are passed with the command line, shell puts each word on the command line into
special variables. For this, the shell uses something called as “positional parameters”; these can be thought
of as variables defined by the shell. They are nine in number, named $1 through $9.
Consider the following statement where program is any executable shell script file and the remaining are
the arguments.
On entering such command, each word is automatically stored serially in the positional parameters thus,
$0 would be assigned program, $1 would be assigned smmit $2 networks $3 is and so on till institute which
is assigned to $9
ies
Write program to copy a file using positional parameters
If cp $1 $2
og
Then
ol
Echo “file copied successfully”
hn
Else
c
Te
Fi
FILE TEST
Sh
TEST TRUE IF
-f file file exists and is regular file
-r file file exists and is readable
-w file file exists and is writable
-x file file exists and is executable
-e file file exists
-s file file exists and has as be greater than zero bytes
-L file file exists and is symbolic link
F1 –nt f2 f1 is newer than f2
F2 –ot f2 f1 is older than f2
F1 –ef f2 f1 is linked to f2
MISCELLANEOUS
Format options Purpose of Option Output
ies
date +%a Displays Weekday name in short (like Mon, Tue, Wed) Thu
date +%A Displays Weekday name in full short (like Monday, Tuesday) Thursday
date +%b Displays Month name in short (like Jan, Feb, Mar ) Feb
og
date +%B Displays Month name in full short (like January, February) February
date +%d Displays Day of month (e.g., 01) 07
ol
date +%D Displays Current Date; shown in MM/DD/YY 02/07/13
date +%F Displays Date; shown in YYYY-MM-DD 2013-02-07
hn
date +%H Displays hour in (00..23) format 23
date +%I Displays hour (01..12) format 11
date +%j Displays day of year (001..366) c 038
Te
date +%m Displays month (01..12) 02
date +%M Displays minute (00..59) 44
ai
date +%U Displays week number of year, with Sunday as first day of week (00..53) 05
Sh