Basic Unix Commands
Basic Unix Commands
Subhasis Samantaray
CONTENTS
2
Unix Operating System
Shell
Kernel
Hardware
In UNIX, the operating system is broken into three pieces: the kernel, the shell,
and the built-in utilities. The kernel is responsible for low level hardware
communication, the shell provides human users with a user-friendly interface, and
the built-in utilities provide basic tools for doing work.
3
Kernel
Manages:-
1. System resources
2. Allocates time between user and processes
3. Decides process priorities
4
Shell
•Korn Shell, Bourne Shell, C Shell are various shells used by Unix users
5
6
User login process
Unix booted.
Program Unix(kernel) is booted into main memory, and remains active till the
computer is shut down
Program init runs as a background task and remains running till shutdown
‘init’ scans file /etc/inittab , which lists the ports with terminals and their
characteristics and returns an active open terminal to ‘init’.
‘init’ calls program ‘getty’, which issues a login prompt in the monitor
7
User login process
8
Basic Unix commands
-Login
-Change password ( Passwd )
-Check the date and time (date)
-Check the present working directory (pwd)
-Check the teminal ( tty & stty)
-Check the system uptime ( uptime)
-Check the user details (finger)
-Change the user details (chfn)
-Get the details of current loggedin users ( Who,Whoami,w )
-Get the identification details ( id )
-Check the name and flavour of the OS ( uname )
-Check the calendar ( Cal )
- Banner (banner)
-host name ( hostname )
-domain name (domainname,dnsdomainname,nisdomainname,ypdomainname )
-clear ( To clear screen )
9
passwd
10
date
date command is used to print or set the system date and time
11
Date - Example
12
pwd,tty,stty,uptime,finger
tty command is used to print the file name of the terminal connected to
standard input
13
Example : pwd,tty,stty,uptime,finger
14
chfn,who
15
Run levels
16
Example : chfn,who
17
whoami,w,id
18
Example : whoami,w,id
19
uname,cal,clear
uname - print system information
20
Example : uname,cal,clear
21
hostname, domainname , dnsdomainname , nisdomainname , ypdomainname
22
Questions ???
1) How to get the OS name ?
2) How to know since when the server is up ?
3) How to get the last boot time of server ?
4) How to get the details of user ?
5) How to know who all are currently logged in and which program they are executing
currently ?
6) How to get the current date and time ?
7) How to get yesterday’s date ?
8) How to get tomorrow’s date ?
9) How to print the date in the following format ?
Todays date is : YYYY-mm-dd:HH-MM-SS
10) How to change the users information ?
11) How to get the id of a particular user ?
12) How to know the present working directory ?
13) How to know which terminal is associated with your current session ?
14) How to get the current terminal settting details ?
15) How to see the calendar of March 1999 ?
16) How to see the calendar for the year 1992 ?
17) How to get the hostname ?
18)How to get the FQDN (Fully Qualified Domain Name) ?
23
How to set arrow keys and backspace ?
Setting arrow keys :
set -o emacs
case "$TERM" in
xterm*|dec-vt220|vt100)
alias __A=^P
alias __B=^N
alias __C=^F
alias __D=^B
;;
hpterm|hp|700*)
alias _A=^P
alias _B=^N
alias _C=^F
alias _D=^B
esac
stty erase ^?
24
File management
25
cat
cat - concatenate files and print on the standard output
To create a file :
cat >filename
After entering the text ,Press [ ctrl + d ] to save and exit
cat >>filename
After entering the text ,Press [ ctrl + d ] to save and exit
Redirection Example :
Let you want to redirect the output of cal command to cal.out file .
cal >cal.out
cat cal.out
26
cat
Indirection example :
Let Qwest.txt is a existing file .You want to cretate a new file WMAIP.txt which will have the same contents as
Qwest.txt .
cat >example.txt<<EOF
Enter test
.
.
EOF
27
cat command
Commands Significance
cat >file1 Creates file file1 where a user enters text and presses <Ctrl-D> to end text editing
cat >>file1 Append lines to existing content of file : file1 and is ended when <Ctrl-D> is pressed
cat file1>file2 Copies the contents of file : file1 into new or existing file : file2
cat file1 file2 > Concatenates the content of file1 and file2 and places it into new or existing file
file3 file3
cat file1 >>file2 Appends the contents of file1 after the last line of file2. If file2 does not exist, new
file is created
28
Example : cat ( create,append,redirection,indirection)
29
Example : Here document
30
touch
touch – create blank file ,change file timestamps( access time,modification time)
31
Example : touch
32
Nullify the contents,Create blank file in different ways
>file name
touch filename
cat /dev/null >filename
>filename
cat > filename [ Immediately press ctrl+d to save and exit ,it will create a blank file ]
cat >.filename
touch .filename
33
Example : Nullify the contents,Create blank file in different ways
34
List the file(s) : ls
ls - list directory contents
List information about the FILEs (the current directory by default). Sort entries alphabetically if none of the
options specified
35
Output of ls -li
1) Inode : Physical location of file
2) Type :
The mode displayed with the -e and -l flags is interpreted as follows:
If the first character is:
d The entry is a directory.
b The entry is a block special file.
c The entry is a character special file.
l The entry is a symbolic link, and either the -N flag was specified or the symbolic link did not point to an existing file.
p The entry is a first-in,first-out (FIFO) special file.
s The entry is a local socket.
- The entry is an ordinary file.
3) Permission :
The next nine characters are divided into three sets of three characters each. The first set of three characters show the owner’s
permission. The next set of three characters show the permission of the other users in the group. The last set of three
characters shows the permission of anyone else with access to the file. The three characters in each set indicate, respectively,
read, write, and execute permission of the file. Execute permission of a directory lets you search a directory for a specified file.
Permissions are indicated as follows:
r Read
w Write (edit)
x Execute (search)
-Corresponding permission not granted
The group-execute permission character is s if the file has set-group-ID mode. The user-execute permission character is s if the
file has set-user-ID mode. The last character of the mode (usually x or -) is T if the 01000 (octal) bit of the mode is set (see the
chmod command for the meaning of this mode).
36
Output of ls -li
4) Link count
5)Owner
6)Group
7)Size of the file
8)Time stamp ( Month day time or year month day )
9) File name
37
Example : ls
38
Copy (cp)
39
Example : Copy (cp)
40
Rename : mv , Delete :rm
mv - move (rename) files
To remove a file whose name starts with a - , for example -Qwest , use one of these commands:
rm -- -Qwest
rm ./-Qwest
41
Example : Rename : mv , Delete :rm
42
Links : Hard Link and Symbolic Link (Soft link )
Hard Link :
A link file created with the Linux / Unix ln command that points to a file's inode.
- Childs are not dependant on parent.
-Inode numbers will be the same
-We cant create hard link to directories.
Symbolic Link:
Also known as a soft link or symlink, a symbolic link is a Linux / Unix file created with the ln
command that links to another file using the path. Unlike a hard link, a symbolic link can link to
any file on any computer.
- Childs are dependant on parent. If you will remove the the source/parent file ,the child file or
link will be dangled.
-Inode numbers are different
-We can create soft/symbolic link to directories.
43
Links : Hard Link and Symbolic Link (Soft link )
To create symbolic link to a file :
ln –s sourcefile newlink
ln –s sourcedir newlink
ln sourcefile newlink
cp –l sourcefile newlink
You can use cp command with –s option to create a soft link/symbolic link.
cp –s sourcefile newlink
The link and unlink commands link and unlink files and directories. Only super-users can use these commands on directories.
44
Example : Symbolic link or soft link
45
Example : Symbolic link or soft link to directories
46
Example : Hard Link
47
Questions ???
1) Cretate a file using cat command ? What is the difference ctrl+d and ctrl+c ( when you are using the ctrl
keys to save and exit )??
2) How to append contents to a existing file?
3) How to change the modification time of a file ?
4) Change the modification time of Qwest.ext file as 1999-Oct-10 23:25 if it exists !!
5) How many ways you can create a blank file ?
6) Cretate file “ My documents” ?
7) Create a file –filename . List ,rename and delete the same file .
8) What is the difference between hard link and soft link ?
9) How to get the inode number of the file ?
10) Explain the output of ls –li .
11) How to get the access time and modfication time of a file ?
12)How to get the file size in kb,mb,gb ??
13)How to list the contents of a directory in a single column ?
14)How to create a hidden file and how to list the file ?
15)How to copy a file with the existing time stamp of source file ? i.e : time stamp of source and destination
file should be the same ..
16)Explain indirection,Redirection,Here document .
17)Explain Link count field .( output of ls –l command ) ?
18) How to copy a file without using cp command ?
19) How to create a hard/soft link to a file without using ln command ?
20)What is link and unlink command ?
48
Directory management
49
Create directory ( mkdir )
50
Create directory ( mkdir )
To create a directory :
mkdir DIR_NAME
mkdir –p /DIR/STRUCTURE/
51
Example : Create directory ( mkdir )
52
Rename (mv) , Remove/Delete ( rmdir ,rm -rf ) the directory
mv - move (rename)
Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.
Syntax :
mv <SOURCE> <DEST>
mv </SOURCE/*.exm > </DEST/>
rmdir –p - remove DIRECTORY, then try to remove each directory component of that path name.
53
Example : Rename (mv) , Remove/Delete ( rmdir ,rm -rf )
the directory
54
Change directory ( cd ,cd ~ ,cd $HOME ,cd / ,cd .. ,cd . ,cd - ,cd
../.. etc )
cd – To change the directory
cd ~
cd $HOME
cd
cd ~user [ user : currently logged in user ]
To go to root ( / ) directory
cd /
cd ..
cd ../../
cd ../../../
55
Change directory ( cd ,cd ~ ,cd $HOME ,cd / ,cd .. ,cd . ,cd - ,cd
../.. etc )
To go back to the previous working directory :
cd –
cd ~usename
echo $PWD
echo $OLDPWD
56
Example : Change directory ( cd ,cd ~ ,cd $HOME ,cd / ,cd .. ,cd .
,cd - ,cd ../.. etc )
57
Copy file(s) from/to a directory
cp </Path/of/sourcefile> ./
Example :
cp Qwest.txt ./A/B/
cp *.txt ./A/B/
cp –R </Path/of/Dir/*> </Path/of/Destn/>
Example :
cp –R ./Qwest/* ./Qwest_bkp/
58
Move file(s) from/to a directory
To rename a directory :
mv SOURCE_DIR DESTN_DIR
Example :
mv Qwest.txt ./A/B/
mv *.txt ./A/B/
mv ./A/B/*.txt ./
mv Qwest Qwest_bkp
59
Example :
60
Example : Symbolic link or soft link to directories
To create symbolic link to a directory :
ln –s sourcedir newlink
61
- Observe the present working directory
- Create the above directory structure .Let you are in your home directory .Don’t use cd while
creating the directory structure.
- Create files india1 and india2 under india , delhi1 and delhi2 under delhi and likewise under all
other directories.
- Change the directory from home to bangalore.
- Copy file bangalore1 from bangalore to karachi.
- Change directory to india from bangalore.
- Move file delhi1 to mumbai.
- List the contents of mumbai from current directory which is india.
- Copy all files bangalore1 and bangalore2 from bangalore to lahore with a single command.
- View the contents of lahore from india.
- Go back to your home directory and try to open the file using absolute path .
- Change the directory to delhi ,Now try to list the pakistan directory using relative path and
absolute path .
- Try to access/read the files present under pakistan directory using relative path and absolute
path .
62
Questions ??
1) How to create a directory ?
2) Create the directory structure : A/B/C/D ?
3) Create directory “Qwest” with permission 700 ?
4) Rename the directory Qwest to Qwest_bkp ?
5) Create a directory WMAIP inside Qwest .
6) Copy the Whole Qwest directory to Qwest_bkp ?
7) Explain cd - ? How it works ?
8) How to go back to home directory ?
9) How to copy a directory recursively ?
10) How to remove a non empty directory ?
11) How to remove a empty directory ?
12) How to create a link to a directory ?
13) How to go to the root directory ?
14) How to go to other user’s home directory ?
15) Explain mkdir –p and rmdir –p ?
16) Explain about the following SHELL variables :
HOME ,PWD,OLDPWD
17) Create a directory –Qwest ?
18) Remove the directory –Qwest ?
19) How to create a hidden directory ?
20) What is absolute path and relative path ?
21) Try to create a directory under / ( root ) drectory .Notice the error message .
63
Permission
64
The chmod command modifies the mode bits and the extended access control lists (ACLs) of the specified files or
directories. The mode can be defined symbolically or numerically.
Symbolic Mode :
To specify a mode in symbolic form, you must specify three sets of flags. Note: Do not separate flags with spaces.The first set of
flags specifies who is granted or denied the specified permissions, as follows:
u File owner.
g Group.
o All others.
a User, group, and all others. The a flag has the same effect as specifying the ugo flags together. If none of these flags are
specified, the default is the a flag and the file creation mask (umask) is applied.
The second set of flags specifies whether the permissions are to be removed, applied, or set:
The third set of flags specifies the permissions that are to be removed, applied, or set:
r Read permission.
w Write permission.
x Execute permission for files; search permission for directories.
s Set-user-ID-on-execution permission if the u flag is specified or implied. Set-group-ID-on-execution permission if the g flag is
specified or implied.
t For directories, indicates that only file owners can link or unlink files in the specified directory. For files, sets the save-text attribute.
65
Examples:
1. To add a type of permission to several files:
This adds write permission for group members to the files chap1 and chap2.
This denies group members and others the permission to create or delete files in mydir (go-w) and allows
group members and others to search mydir or use it in a path name (go+x). This is equivalent to the
command sequence: chmod g-w mydir chmod o-w mydir chmod g+x mydir chmod o+x mydir
This gives read, write, and execute permission to the user who owns the file (u=rwx). It also denies the
group and others the permission to access cmd in any way (go=). If you have permission to execute the
cmd shell command file, then you can run it by entering: cmd
66
Numeric representation of permissions
Value Significance
4 Read permission
2 Write permission
1 Execute permission
To recursively descend directories and change file and directory permissions use –R option .
67
chmod - change file access permissions
Example Significance
chmod 744 file1 Grant all permissions to : User, and read permission to group and others
chmod 776 Grant all permission to user and group, read and write permission to
others
chmod 777 file1 Grant all permission to all
68
Few more Examples:
chmod +x myfile
Same as the above command, but specifically specifies user, group and other.
Gives the user read permission, and removes all other permission.
These permissions are specified in octal, the first char is for the user, second for the group and the third is for other.
Gives user full access, group read and write access, and other read access.
Gives user full access, group read and execute permission, and other, execute permission.
chmod +s myfile
Remove read and execute permissions for the group and other.
69
Default file/directory permission ,umask
The default umask 0002 used for normal user. With this mask default directory permissions
are 775 and default file permissions are 664.
The default umask for the root user is 0022 result into default directory permissions are 755
and default file permissions are 644.
umask
70
Example :chmod ,umask
71
chgrp, chown, chgrp
chgrp - change group ownership
Example :
72
To use Set-ID Modes:
When the cmd command is executed, the effective user and group IDs are set to those that own the cmd
file. Only the effective IDs associated with the child process that runs the cmd command are changed. The
effective IDs of the shell session remain unchanged. This feature allows you to permit access to restricted
files. Suppose that the cmd program has the Set-User-ID Mode enabled and is owned by a user called dbms.
The user dbms is not actually a person, but might be associated with a database management system. The
user betty does not have permission to access any of dbms’s data files. However, she does have permission
to execute the cmd command. When she does so, her effective user ID is temporarily changed to dbms, so
that the cmd program can access the data files owned by the user dbms. This way the user betty can use the
cmd command to access the data files, but she cannot accidentally damage them with the standard shell
commands.
When run Unix executables can use the effective rights of a different user or group. This is shown by
having an 's' rather than 'x'. For example:
ls -l /bin/su
-rwsr-xr-x 1 root root 60820 Oct 4 2006 /bin/su
When su is run it runs with the same rights as the user root.
Any program which is suid or sgid must be written very carefully to make sure that it can not be abused by
malicious users to do things they shouldn't.
73
The sticky bit - /tmp directory
Normally (without 't') any user who has write permission to a directory can delete
any files in the directory regardless of who owns it, even if they can't read or write to
the file.
With 't' set, only the owner of a file can delete it.
ls -ld /tmp
drwxrwxrwt 9 root root 4096 Jan 22 21:31 /tmp
chmod +t directory
chmod -t directory
74
Questions ??
1) What is the default directory permission ?
2) What is the default file permission ?
3) What is the default umask value ?
4) How to change the umask value ?
5) How umask value plays the role in changing the permission ?
6) Let I want to set the umask value as 0077 permanently .What are the steps to do it ? After the set up what will be the
directory and file permissions ?
7) How to change the group of a file/directory ?
8) How to change the owner of the file or directory ?
9) Set the following permission to Qwest.txt
user : read,write
group:read
others: none
Set the permission in 2 ways .
10) Explain the octal representation ?
11) What is set id mode ?
12) What is sticky bit ?How to set sticky bit ?
13) How to revoke sticky bit ?
14) Cretate a directory Qwest_EX with 600 permission ,then try to cd to that directory and analyse the error message .
15) Let you are the owner of a directory .The directory permission is 600 .Will you able to list the contetnts ?
16) How many ways we can grant read,write,execute permission to all on Qwest.txt ( Qwest.txt is text file ) ?
17) What is the default permission for symbolic link(s) ?Can we change the permission of symbolic links ?
18) What will happen if you change the permission of symbolic/soft link (s) ?
19) Let in a directory you have 30 regular text files and 5 symbolic/soft links and 10 directories . Recursively change the
permission of regular files and directories to 700 without any change to linked files .
75
Strange output :
76
File/Text processing commands
- head
- tail
- pg
- more
- less
- cut
- paste
- tr
- sort
- uniq
- comm
- cmp
- diff
- sdiff
- join
- col
- seq
- wc
77
head,tail
78
Example : head,tail
79
pg
80
more,less
81
cut
82
Example : cut
[linux1@HMLINUX1 WMAIP]$ cat Qwest.txt
1:Anil:SE:Qwest
2:Srikanth:LEAD:Qwest
3:Subhasis:SSE:Qwest
4:Sudipta:Manager:Qwest
[linux1@HMLINUX1 WMAIP]$ cat Qwest.txt|cut -c1
1
2
3
4
[linux1@HMLINUX1 WMAIP]$ cat Qwest.txt|cut -d":" -f2
Anil
Srikanth
Subhasis
Sudipta
[ [linux1@HMLINUX1 WMAIP]$ cat Qwest.txt|cut -d":" -f2-4
Anil:SE:Qwest
Srikanth:LEAD:Qwest
Subhasis:SSE:Qwest
Sudipta:Manager:Qwest
[linux1@HMLINUX1 WMAIP]$ cat Qwest.txt|cut -d":" -f1,3
1:SE
2:LEAD
3:SSE
4:Manager
[linux1@HMLINUX1 WMAIP]$ cat Qwest.txt|cut -d":" -f1,3,2
1:Anil:SE
2:Srikanth:LEAD
3:Subhasis:SSE
4:Sudipta:Manager
83
Example : cut
84
paste
85
Example : paste
[linux1@HMLINUX1 WMAIP]$ cat Qwest.txt
1:
Anil
2:
Srikanth
3:
Subhasis
[linux1@HMLINUX1 WMAIP]$ paste -s -d' \n' <Qwest.txt >Qwest.out
[linux1@HMLINUX1 WMAIP]$ cat Qwest.out
1: Anil
2: Srikanth
3: Subhasis
[linux1@HMLINUX1 WMAIP]$ cat Qwest.1.txt
:SE
:LEAD
:SSE
[linux1@HMLINUX1 WMAIP]$ paste Qwest.out Qwest.1.txt
1: Anil :SE
2: Srikanth :LEAD
3: Subhasis :SSE
86
Example : paste
87
tr
tr - translate or delete characters
Translate, squeeze, and/or delete characters from standard input, writing to standard output.
88
Examples: tr
$ cat Qwest.txt
Anil
Srikanth
To change all the lower case to upper case :
90
Questions??
1) Let source file(add.txt) is
Name:Anil
City:Bangalore
Phone:12345
Name:Nithin
City:mumbai
Phone:23456
The required output is :
Anil Bangalore 12345
Nithin Mumbai 23456
4) Contents of Testdata is :
<Name>Anil</Name>
<DEPTH>WMAIP</DEPT>
<LOC>BANGALORE</LOC>
<MOB>888-998-9076</MOB>
<Name>SHREY</Name>
<DEPTH>QBAIP</DEPT>
<LOC>NOIDA</LOC>
<MOB>888-998-9075</MOB>
The required output is :
Anil WMAIP BANGALORE 888-998-9076
SHREY QBAIP NOIDA 888-998-9075
Using the same input file ,How to get the following outut ?
91
Example :
92
sort
93
Changing the field delimiter
94
Defining the sort field
The first field of each line starts at 0 (zero); the second is 1 (one) and so
on. To define which field to sort on you give the position of the field at which
to start the sort followed by the position at which to end the sort. The position
at which to start the sort is given as the number of fields to skip to get to this
position. For example
+2 tells sort to skip the first two fields.
The position at which to stop the sort is given as the number of the field at
the end of which the sort stops. For example
-3 tells sort to stop the sort at the end of field three.
To sort on the third field of a line use the definition:
+2 -3 To sort on the fields 5 and 6:
+4 -6
95
Sorting on a specific part of a field
To define which part of a field to sort on, give the position in the field at
which to start the sort followed by the position in the field at which to end the
sort.
The position at which to start the sort is given as the number of fields to
skip followed by the number of characters to skip. For example:
+2.3 tells sort to skip the first two fields and the first three characters of
field 3.
The position at which to stop the sort is given as the number of the field
followed by number of the character in that field at which the sort is to stop.
For example:
-3.6 tells sort to stop the sort at the 6th character in field three.
To sort on the fourth and fifth characters of field three:
+2.3 -3.6
96
Saving the results of a sort to a file
sort sends its results directly to your screen. To save them to a file use
the -o option. For example:
sort -o sort.out addresses
This saves the results of sorting the file addresses in the file sort.out.
You can check if a file has already been sorted with the -c option. For
example:
sort -c +2 -3 accounts
This checks to see if the file accounts has already been sorted on the third
field of each line. You will only get a message if the file is not sorted
according to this sequence.
97
Example : sort
98
Example: Sort
99
uniq
100
Example : uniq
101
Example : uniq
102
Questions ??
1) How to get the list of unique records from a file ?
2) How to get the list of duplicate records from a file ?
3) How to get the count of each unique record present in a file ?
4) Let in a file we have the following contents .How to get the uniq records using sort ?
1
2
1
3
1
4
4
Required output is :
1
2
3
4
5) What is sort command and explain some useful options of sort command ?
6) How to perform numeric sort ?
7) How to get the list of 5 big size files, Which are present in your present working directory ?
8) Let Qwest.txt file contains 110 lines . Write an one liner which will print the lines 23 to 43 ?
9) What will be the output of
head Qwest.txt
10) What will be the output of
tail Qwest.txt
11) What is tail –f ? When it is required ?
12) What is the purpose of more command ?
13) Explain about less and pg ?
103
comm
104
Questions ???
Contents of Q1.txt is
Anil
Subhasis
Nithin
Contents of Q2.txt is
Anil
Subhasis
Srikanth
1) How to get the records which are present in Q1.txt but not in Q2.txt ?
2) How to get the records which are present in Q2.txt but not in Q1.txt ?
3) How to get the common records present in Q1.txt and Q2.txt ?
4) Explain comm command ?
105
Example : comm
106
cmp
cmp - compare two files
The cmp utility compares two files of any type and writes the results to the standard output.
By default, cmp is silent if the files are the same; If they differ, the byte and line number at which
the first difference occurred is reported.
1 The files are different; this includes the case where one file is iden-
tical to the first part of the other. In the latter case, if the -s
option has not been specified, cmp writes to standard output that EOF
was reached in the shorter file (before any differences were found).
107
Example : cmp
108
diff
109
Example : diff
110
Sdiff,col,seq
sdiff - find differences between two files and merge interactively
Col filters out reverse (and half reverse) line feeds so the output is in the correct order with only forward and half forward line
feeds, and replaces white-space characters with tabs where possible.
-b Do not output any backspaces, printing only the last character written to each column position.
-f Forward half line feeds are permitted (ââfineââ mode). Normally characters printed on a half line boundary are printed on the
following line.
-p Force unknown control sequences to be passed through unchanged. Normally, col will filter out any control sequences from
the input other
than those recognized and interpreted by itself, which are listed below.
-x Output multiple spaces instead of tabs.
Example :
If you are using bash shell ( Version 3.0 onwards ) you can use the following command to generate the sequence of numbers .
$ echo {1..10}
1 2 3 4 5 6 7 8 9 10
111
wc
wc - print the number of newlines, words, and bytes in files
Example:
$ cat qwest.txt
Qwest Software services
Srikanth
Anil Nithin
Subhasis
$ wc -l qwest.txt
6 qwest.txt
$ cat qwest.txt|wc -l
6
$ cat qwest.txt|wc -c
56
$ cat qwest.txt|wc -m
56
$ cat qwest.txt|wc -w
7
112
Questions ??
1) What is cmp command ?
2) What is the purpose of diff command ?
3) What is the purpose of sdiff command ?
4) How to generate the sequence of numbers ?
5) What is the exit status of cmp command ?
6) What is the exit status of diff command ?
7) How to get the exit status of the following command ?
diff Q1.txt Q2.txt
8) How to get the exit status of the following command ?
cmp Q1.txt Q2.txt
9) What is the purpose of col –p ?
10) How to get the following output using seq command ?
1:2:3:4:5:6:7:8:9:10
11)How to get the record/line count of a file ?
12)How to know how many lines are present in a file ?
13)How to know how many words are present in a file ?
14)How to know how many characters are present in a file ?
15)How to know how many alpha numeric characters are present in a file ?
113
EDITOR
vi
vim
emac
114
VI EDITOR
115
Modes of Operation Ex mode
116
Mode of Operation
Command mode : Default mode when a file is opened using vi. All the
keys pressed by the user are interpreted as user commands
117
Command Mode
R,R,I,I,c,C,o,O,
s,S,a,A
Enter :
Esc
118
Vim Tips and Tricks
119
First Session with vi
120
Step 1 : Create a new file by typing the following command from the OS
Prompt : vi newfile
122
Step 3 : Press ‘:’. The cursor takes to the ‘ex’ mode at the command line.
Enter ‘wq’ and press enter.
Inserting Texts
Cmd Significance
i Appends text from the left of the current cursor position
I Appends text at the start of the current line.
a Appends text from the right of the current cursor position
124
Changing Texts
Cmd Significance
<n>r Replaces <n> characters from current cursor posn. with inserted text
R Replaces text from cursor to right
<n>s Replaces <n> characters from cursor with entered text
<n>S Replaces <n> lines from the current cursor line with entered text
C Change from current cursor posn. to end of line with the text entered
<n>cw Changes <n> words from the current cursor position with text entered
<n>cc Replaces <n> lines from the current cursor line with entered text
cG Changes from current cursor position to end of the file with entered text.
125
Command Mode
Deleting texts/lines
Cmd Significance
<n>x Deletes <n> characters from current cursor position
<n>dd or <n>D Deletes <n> lines counting from current cursor line to below
d$ Deletes from current cursor position to end of line
dG Deletes from current cursot position to end of file
d<n>G Deletes from current line to line no <n>
df<char> Deletes from current cursor position to first occurrence of character <char>
d/<pattern> Deletes from cursor upto the first occurrence of string <pattern> in forward
direction
d?<pattern> Deletes from cursor upto the first occurrence of string <pattern> in backward
direction
126
Moving/Copying Texts
Cmd Significance
<n>yy or <n>Y Yank <n> lines starting from current line onwards into undo buffer
<n>yw Yank <n> words starting from current cursor position onwards into undo buffer
y$ Yank from current cursor position to end of the line in undo buffer
yG Yank from current cursor position to end of the file in undo buffer
“a<n>yy Yank <n> lines starting from current line onwards into buffer named a
p Paste the contents of undo buffer( as a result of deleting or yanking) after the cursor
position
P Paste the contents of undo buffer( as a result of deleting or yanking) before the cursor
position
127
Navigation in same line
Cmd Significance
<n>h Moves cursor left to nth previous character w.r.t. the current cursor position
<n>l Moves cursor right to nth next character w.r.t. the current cursor position
<n>b Moves cursor left to start of nth previous word w.r.t the current cursor position. Punctuation
marks are taken into account.
<n>w Moves cursor right to start of nth next word w.r.t the current cursor position. Punctuation
marks are taken into account.
<n>e Moves cursor right to end of nth next word w.r.t the current cursor position. Punctuation marks
are taken into account.
f<ch> Move the character to the next character <ch> on same line
F<ch> Move the character to the prv. character <ch> on same line
t<ch> Move the character to one column before the next character <ch> on same line
T<ch> Move the character to one column after the next character <ch> on same line
; Repeats search in the same direction along which the prv. Search was made using f/t
128
Cmd Significance
, Repeats search in the opposite direction along which the prv. Search was made using f/t
<n>W Moves cursor right to start of nth next word w.r.t the current cursor position. Punctuation
marks are ignored
<n>E Moves cursor right to end of nth next word w.r.t the current cursor position. Punctuation marks
are ignored
129
Navigation across lines
Cmd Significance
<n>j or Move the cursor down to the <n>th next line in the same column
<n>^n
<n>k or Move the cursor up to the <n>th prv line in the same column
<n>^p
H Moves the cursor to the top line of the screen
L Moves the cursor to the last line of the screen
M Moves the cursor to the middle line of the screen
<n>G Moves to line number <n>
+ Moves the cursor to next line’s first non-blank character
- Moves the cursor to previous line’s first non-blank character
130
Redraw screen
Cmd Significance
z- Makes the current line the last line of the screenand redraws the screen
z+ Makes the current line the first line of the screenand redraws the screen
z. Makes the current line the middle line of the screenand redraws the screen
/pattern/z- Find the next occurrence of <pattern> and make that last line of the screen
131
Scrolling across pages
Cmd Significance
<n>^f Move forward by <n> screens
<n>^b Move backward by <n> screens
<n>^d Move forward by <n> number of half screens
<n>^u Move backward by <n> number of half screens
<n>^e Scroll window down by <n> lines
<n>^y Scroll window up by <n> lines
132
Pattern searching
Cmd Significance
/pattern Searches for specified <pattern> forward. IF end of file is reached, search wraps
around.
?pattern Searches for specified <pattern> backward.
n Repeat the last search in the same direction as was specified in the last search
N Repeat the last search in the opposite direction as was specified in the last search
/pattern/+<n> Positions the cursor <n> number of lines after the line where the specified <pattern>
is found
/pattern/-<n> Positions the cursor <n> number of lines before the line where the specified
<pattern> is found
% Find the matching braces or parenthesis
133
Joining lines
Cmd Significance
<n>J Joins current line and <n> lines below it together to form a single line
Undo changes
Cmd Significance
u Undo last change
U Undo all the changes in the current line
Marking text
Cmd Significance
m<char> Marks position of the file with mark <char>
‘<char> Moves to portion of the file marked with <char>
“ Toggle to most recently marked location
134
Restoring previously deleted line
Cmd Significance
“<n>p Paste the content of <n>th last delete ( n<=9)
“1pu.u.u… Till the last change is found
Filtering texts
Cmd Significance
!<n>G sort Sort from current line to line no. <n>
!<n>G tr ‘[a-z]’ ‘[A-Z]’ Translates all the characters from current line to line <n> to uppercase
!! tr ‘[a-z]’ ‘[A-Z]’ Translates all the characters of current line to uppercase
Repeat factor
Cmd Significance
<n>i<ch> Inserts <ch> character <n> number of times in input mode at a stretch
135
Miscellaneous in command mode
Cmd Significance
~ Change the character under cursor from lowercase to uppercase and vice versa
. Repeat the last change
<n>. Repeat the last action ‘n’ times
<< Shift current line to shift width character left
>> Shift current line to shift width character right
136
Options available with vi command
Cmd Significance
vi –r <filename> Recover the file <filename> as much as possible after system crash and
open it
vi –R <filename> Open the file <filename> in read-only mode
vi +<n> <filename> Opens the file <filename> with cursor positioned in line number <n>
vi + <filename> Opens the file <filename> with cursor at the last line
vi –w<n> <filename> Opens file <filename> in vi mode with window size of <n> number of lines
vi +/<pattern> <filename> Opens file <filename> in vi editor and places the cursor at first occurrence
of pattern <pattern>
vi –x <filename> Opens encrypted file <filename> in vi mode and asks for the password
before opening that
137
Ex Mode
138
Cmd Significance
:.,.+<n>w <newfile> Appends from current line to <n> number of lines below it into
file <newfile>
:.,.+<n>w >> <nextfile> Appends from current line to <n> number of lines below it after the last
line of the file <nextfile>
:q Quits the file editing in vi, provided no unsaved change remains
:q! Quits vi neglecting all the unsaved changes made to the file
:wq or :x Save the unsaved changes in the opened file and quit vi editor
139
Navigating to desired line
Cmd Significance
:<n> Custor moves to line number <n>
140
Examples of Search and Replace
Example Significance
:%s/ex/vi/c Substitutes 1st occurrence of string ‘ex’ with ‘vi’ by showing them and
asking for confirmation. When each string will be shown with pause in
cursor, press ‘y’ for substitution
:%s /<amaze \ >\/delight/g Replaces ‘amaze’ , where available as a full word, with ‘delight’. Note,
any word like ‘amazed’ will not be replaced
:g!/complete/s/$/To be done/ Append the string ‘To be done’ at the end of all lines not containing
the string ‘complete’
141
Example Significance
:g/vi/s/^/editor/ Append the string ‘editor’ at the first of all lines containing the
string ‘vi’
:%s/$/ : see my note/g Appends the string ‘: see my note’ at the end of all lines
:g/^….$/d Deletes all lines containing 4 letters
:g/^..o/d Deletes all lines with ‘o’ as 3rd character
:%s/…$//g Delete the last three character of every line
Command Significance
:r <nextfile> Reads the contents of the file <nextfile> below current line
:r! <command> Places the output of the command <command> below the current
line
Mapping
Command Significance
:map g :w^M Pressing ‘g’, one wants to save the file(:w is for saving, and ^M is for
pressing Enter key. While writing it in the command line, write ^V^M)
:map z i^M^[ When you position your cursor to any character in a line and press ‘z’ , the
line will be broken from that point and two lines will be formed. The control
will remain in command mode
(^[ represents <Escape> key)
:map z :w^M:!%^M Pressing ‘z’ in command mode saves the file and executes it in one shot
145
Setting environmental variables for vi
Works in ex mode.
To set an environment variable to customize vi, the following syntax needs to
be followed:-
:set <env.variable> [= <value>]
146
Environment Significance
variables
autoindent(ai) Newly inserted lines of text are indented to the same distance from left margin as
the preceding line. Opposite of this option is noautoindent(noai)
autowrite(aw) Automatically saves the unsaved changes in a file before opening the next file with :n
or using a shell command with :! <command>. The opposite to this option is
noautowrite(noaw)
errorbells(eb) Sounds the bell when error occurs. Opposite is ‘noeb’
exrc(ex) Allows an .exrc file in the current directory to override the .exrc file in user’s home
directory. Opposite is ‘noex’
list Displays special characters in the screen: tabs are shown as ^I, end of line are
marked with ‘$’. Opposite is ‘nolist’
147
Environment variables Significance
report=<val> When any operation affects more lines than this settings, message is
displayed
scroll=<val> Number of screen lines to scroll
wrapmargin(wrm)=<val> When set to a value >0 , carriage returns are inserted automatically when
the cursor gets to within that number of spaces from the right edge of
the screen
148
One can store all the values for environment variables, all the key
mappings and all the abbreviations in a file ‘.exrc’ under the home
directory for the user.VI looks for this file on startup and executes the
instructions as ex mode commands.
149
view
Syntax : view <filename>
150
Questions ??
1) How to view a file ?
2) Suppose you opened a file with view command and did some modification .How to save the
modifications ?
3) How to save a file ?
4) Suppose 2 users opened the same file .one of the user modified some contents .The other user wants to
see the content without exiting from the vi editor .What is the command to refresh/ see the modified
contents of the file ?
5) How to insert a text to a file ?
6) What is the command to come back to the shell temporarily ?
7) What is the command to save and exit from vi editor ?
8) What is the command to exit without save ?
9) What is wq! ?
10) What is q! ?
11) How to go to the last line of a file ?
12) How to go the end of the current line ?
13) How to add a line below and above the current cursor position ?
14) How to go to a specific line ? Let line 10 ?
15) How to append text to the end of a line and in between ?
16) How to join two lines ?
17) How to set the line numbers ?
18) How to unset the line number ?
19) How to move up ,down ,left and right from the cursor position ?
20) How to delete a word ?
151
Questions ??
152
Pattern searching
- grep
- egrep
- fgrep
153
grep, egrep, fgrep
grep, egrep, fgrep - print lines matching a pattern.
Grep searches the named input FILEs (or standard input if no files are named, or the file name - is given) for
lines containing a match to the given PATTERN. By default, grep prints the matching lines.
In addition, two variant programs egrep and fgrep are available. Egrep is the same as grep -E. Fgrep is the
same as grep -F.
-e pattern_list
Specifies one or more patterns to be used ring the search for input.
Patterns in pattern_list must be separated by a NEWLINE character.
-i Ignore case distinctions in both the PATTERN and the input files.
154
Useful options of grep:
-L --files-without-match , Suppress normal output; instead print the name of
each input file from which no output would normally have been printed.
The scanning will stop on the first match.
-n --line-number,Prefix each line of output with the line number within its
input file.
-o --only-matching,Show only the part of a matching line that matches
PATTERN.
-R, -r --recursive,Read all files under each directory, recursively; this is
equivalent to the -d recurse option.
-s Suppresses error messages about nonexistent or unreadable files.
-w Select only those lines containing matches that form whole words.
The test is that the matching substring must either be at the beginning of
the line, or preceded by a non-word constituent character.
155
REGULAR EXPRESSION
\ (BackSlash) turn off the special meaning of the next character, as in \^.
[ ] (Brackets) match any one of the enclosed characters, as in [aeiou]. Use Hyphen "-" for a
range, as in [0-9].
[^ ] match any one character except those enclosed in [ ], as in [^0-9].
156
Example
157
Example
158
Example:
1)Search /etc/passwd for linux1 user:
$ grep linux1 /etc/passwd
2)You can force grep to ignore word case i.e match linux1, Linux1, LINUX1 and all other combination with -i option:
You can search recursively i.e. read all files under each directory for a string "10.140.7.1"
When you search for linux1, grep will match TRNlinux1, Linux123, etc.
You can force grep to select only those lines containing matches that form whole words i.e. match only linux1 word:
159
Example:
6)Count lines when words has been matched
grep can report the number of times that the pattern has been matched for each file using -c (count) option:
7) you can use -n option, which causes grep to precede each line of output with the number of the line in the text file from which it was obtained:
9) grep command often used with pipes. For example print name of hard disk devices:
# dmesg | egrep '(s|h)d[a-z]'
However, above command can be also used as follows without shell pipe:
# grep -i 'Model' /proc/cpuinfo
11)Use the -l option to list file name whose contents mention main():
$ grep -l 'main' *.c
160
Questions ??
1)How to get the password file entry for linux1 user?
2)Let the user name is unknown .It may be linux1, Linux1, LINUX1 .In that scenarion how to get the password file entry for linux1 user ?
3)How to search recursively /etc/ directory ,To get the list of files containing string "10.140.7.1" ?
4)When you search for linux1, grep will match TRNlinux1, Linux123, etc.How to force grep to select only those lines containing matches that form whole
words i.e. match only linux1 word: ?
5) How to use grep to search 2 different words in a file Qwest.txt .The words are : Anil and srikanth ?
8)How to print the line that does not contain Qwest string ?
9)How to get the name of files which conains the string "Nithin" ?
10) grep command often used with pipes. For example print name of hard disk devices:
# dmesg | egrep '(s|h)d[a-z]'
However, above command can be also used as follows without shell pipe:
# grep -i 'Model' /proc/cpuinfo
161
Searching and Archiving
Searching files :
find
Archiving commands
- tar
- cpio
- zip
- unzip
- gzip
- gunzip
- compress
- uncompress
- zcat and gzcat
162
find
find - search for files in a directory hierarchy
-type <c>
File is of type c:
-perm mode File's permission bits are exactly mode (octal or symbolic).
Symbolic modes use mode 0 as a point of departure.
-perm -mode All of the permission bits mode are set for the file.
-perm +mode Any of the permission bits mode are set for the file.
163
find
-newer file
File was modified more recently than file. -newer is affected
by -follow only if -follow comes before -newer on the command
-name pattern
Base of file name (the path with the leading directories
removed) matches shell pattern pattern. The metacharacters
(`*', `?', and `[]') do not match a `.' at the start of the base name.
To ignore a directory and the files under it, use -prune; see an
example in the description of -path.
164
find
-size n[cwbk] File uses n units of space. The following suffixes can be
used:
165
find
-maxdepth levels
166
Example:find
1) Search the file Qwest.txt from current directory downwards and print it ?
2) Find all files which begin with 'S' or 'N' from current directory downwards and print them ?
3)Search directories called backup from /opt/proj directory downwards and print them ?
4)Search normal files called test.log /opt/proj directory downwards and print them ?
5) Search character special files called test.log /opt/proj directory downwards and print them ?
167
Example:find
6) Search block special files called test.log /opt/proj directory downwards and print them ?
7) Search all directories from /opt/proj directory downwards for files whose inode number is 3456 ?
8) Search root directory downwards for files which have exact link count 2 ?
9) Search root directory downwards for files which have less than 2 links ?
10) Search root directory downwards for files which have more than 2 links ?
168
Example:find
11) Search current directory downwards for all files whose owner is Qwest and group is default ?
12)Search current directory downwards for all files whose owner is Qwest or name is Qwest.txt ?
13)Search in current directory downwards for all files which have permissions 777?
14)Search in current directory downwards for all files whose size is 10 blocks?
15)Search in current directory downwards for all files whose size is 10 bytes (characters)?
16)Search in current directory downwards for all files whose size is greater than 10 bytes?
169
Example:find
17)Search in current directory downwards for all files whose size is less than 10 bytes?
18)Search in current directory downwards for all files which were accessed exactly 7 days back
?
19)Search in current directory downwards for all files which were accessed more than 7 days
ago ?
20)Search in current directory downwards for all files which were modified more than 7 days
ago ?
170
Example:find
21)Search in current directory downwards for all files whose name is core and remove the files
?
{} -- > Means files returned by find command would become arguments for rm.
22)Search in current directory downwards for all files whose name is core and remove the files
? If confirmation is required before removing the files use -ok
171
Example:find
23) Search in current directory downwards for all files which are
modified after /tmp/Qwest.txt ( newer than /tmp/Qwest.txt) ?
172
Find : -prune Example
$ find . -type f -print
./C/c.txt
./F/F.txt
./E/E.txt
./A/a.xtx
./D/d.txt
./B/b.txt
./ttt.txt
$ find . -path ./B -prune -o -path ./C -prune -o -type f -print
./F/F.txt
./E/E.txt
./A/a.xtx
./D/d.txt
./ttt.txt
$ find . -path ./B -prune -o -path ./C -prune -o -path ./D -prune -o -type f -print
./F/F.txt
./E/E.txt
./A/a.xtx
./ttt.txt
173
Example : find ( -newer , – maxdepth , -prune )
174
Questions ??
1) How to search the file Qwest.txt from current directory downwards?
2) How to find all files which begin with 'S' or 'N' from current directory downwards ?
3) How to search directories called backup from /opt/proj directory downwards ?
4) How to search all directories from /opt/proj directory downwards for files whose inode number is 1234 ?
5) How to search root directory downwards for files which have less than 2 links ?
6) How to search current directory downwards for all files whose owner is Qwest and group is default ?
7) How to search in current directory downwards for all files whose size is greater than 3mb?
8) How to search in current directory downwards for all files which were accessed more than 2 months ago ?
9) How to search in current directory downwards for all files which were modified more than 1 year ago ?
10)How to search in current directory downwards for all files which were modified in last 10 hours ?
11)How to search in current directory downwards for all files which were modified more than 5 hours ago ?
12)Search in current directory downwards for all files whose name is core and remove the files ?
13) What is the difference between xargs and exec ?
14)Search in current directory downwards for all files which are modified after /tmp/Qwest.txt ( newer than
/tmp/Qwest.txt) ?
15)Search only in current directory ( not in sub directories ) for all files which are modified after /tmp/Qwest.txt
( newer than /tmp/Qwest.txt) ?
16)What is the equivalent option for -maxdepth 1 ?
17)Which one of the following command is better and safe ?
find ./ -name "Qwest.txt" -type f -ls
find ./ -name "Qwest.txt" -type f -print |xargs ls -l
175
tar
tar - create tape archives and add or extract files
$ ls -C1
1.txt
Alignment.ksh
Alignment_printf.ksh
mytest
test.data
176
tar
To See the contents of exhisting archive : ( tar –tvf )
$ tar -tvf test.tar
-rw-rw-r-- linux1/linux1 68 2008-09-05 13:52:48 ./1.txt
-rwxrwxr-x linux1/linux1 949 2008-09-08 18:46:20 ./Alignment.ksh
-rwxrwxr-x linux1/linux1 867 2008-09-05 14:36:04 ./Alignment_printf.ksh
-rw-rw-r-- linux1/linux1 5 2008-09-10 16:33:53 ./mytest
-rw-rw-r-- linux1/linux1 240 2008-09-05 14:42:57 ./test.data
177
tar,cpio
178
Example :
179
Example :
180
zip and unzip
zip is a compression and file packaging utility
When given the name of an existing zip archive, zip will replace identically named entries in the zip archive or add entries for new names. For example, if foo.zip
exists and contains foo/file1 and foo/file2, and the directory foo contains the files foo/file1 and foo/file3, then:
will replace foo/file1 in foo.zip and add foo/file3 to foo.zip. After this, foo.zip contains foo/file1, foo/file2 and foo/file3, with foo/file2 unchanged from before.
Another example :
zip also accepts a single dash ("-") as the name of a file to be compressed, in which case it will read the file from standard input, allowing zip to take
input from another program. For example:
-b path Use the specified path for the temporary zip archive. For example:
181
zip and unzip
unzip Qwest.zip
unzip -j Qwest
To extract all FORTRAN and C source files--*.f, *.c, *.h, and Makefile--into
the /tmp directory:
182
Example:
183
gzip and gunzip
184
gzip and gunzip
185
compress / uncompress ,gzcat ,zcat
NB : zcat and gzcat both are same .Most of the recent OS contains zcat only
.
186
Example:
187
Questions ??
188
Process management
- ps
- kill
- nice
- jobs
- fg
- bg
- nohup
- vmstat
- prstat
- iostat
- top
- nmon
- sar
- glance
- pgrep
- pkill
- pwdx
- time
189
ps
190
PROCESS STATE CODES
Here are the different values that the s, stat and state output specifiers (header
"STAT" or "S") will display to describe the state of a process.
191
Description : ( Some of the useful fields )
S The state of the process or kernel thread.
UID Owner/user of the process
PID The process ID of the process.
PPID The process ID of the parent process.
PRI The priority of the process or kernel thread; higher numbers
mean lower priority
STIME The starting time of the process.
TIME The total execution time for the process.
SZ The size in 1KB units of the core image of the process.
TTY The controlling workstation for the process:
- The process is not associated with a workstation.
? Unknown.
WCHAN The event for which the process or kernel thread is waiting or
sleeping.
NI Nice value
ADDR Contains the segment number of the process stack, if normal; if
a kernel process, the address of the preprocess data area.
CMD Contains the command name
192
Example:
193
kill
kill - terminate a process
kill 1095
This sends signal 9, the SIGKILL signal, to processes 2098 and 1569.
The SIGKILL signal is a special signal that normally cannot be ignored or overridden.
kill -kill 0
This sends signal 9, the SIGKILL signal, to all processes having a process group ID equal to the senders process group ID.
Because the shell cannot ignore the SIGKILL signal, this also stops the login shell and logs you off.
194
kill
4. To stop all processes that you own, enter:
kill -9 -1
This sends signal 9, the SIGKILL signal, to all processes owned by the effective user, even those started
at other work stations and that belong to other process groups. If a listing that you requested is being printed,
it is also stopped.
The name of the kill command is misleading because many signals, including SIGUSR1, do not stop
processes. The action taken on SIGUSR1 is defined by the particular application you are running.
kill -9 PID
Note: To send signal 15, the SIGTERM signal with this form of the kill command, you must explicitly
specify -15 or TERM.
195
Questions ??
1)How to list all process of the user Qwest ?
2)How to list all processes ?
3) Which one is the 1st process ?
4)How to get the current state of the process ?
5)How to identify a zombie process ?
6)How to get the startup time of the process ?
7)How to get the nice value of the process ?
8)How to get the priority of a process ?
9)How to get the current kernel operation of a process ?
10)How to get the pid and ppid of a process ?
11) How to get the owner details of a process ?
12)How to stop a given process ?
13)How to kill a process forcefully ?
14)How to terminate a process ?
15) How to stop several processes that ignore the default signal ?
16) Which command will stop all of your processes and log yourself off ?
17)How to stop all processes that you own ?
18)How to get the list of signals ?
19) How to kill the last back ground job ?
20)How to get the PID of current shell ?
196
nice
197
Jobs,fg,bg
Jobs - Displays status of jobs in the current session.
fg [jobspec/jobid]
Resume jobspec/jobid in the foreground, and make it the current job.
bg [jobspec/jobid]
Resume the suspended job [ jobspec/jobid ] in the background, as if it had
been started with &.
198
Example:
199
nohup,vmstat,iostat,prstat,top,sar,glance,nmon,time
iostat - Report Central Processing Unit (CPU) statistics and input/output statistics for devices and partitions.
top -The top program provides a dynamic real-time view of a running system. It can display system summary information as well as a list of tasks
currently being managed by the kernel.
nmon - nmon is used by system admins and performance analyst to check the system health
Example : time ls
Another example :
$ time date
Tue Jan 26 18:27:58 IST 2010
real 0m0.002s
user 0m0.000s
sys 0m0.001s
200
pgrep,pkill ,pwdx
pgrep, pkill - look up or signal processes based on name and other attributes
Example :
will only list the processes called sshd AND owned by root.
pgrep -u root,daemon
pkill -u username
201
Example:
202
Questions ??
1)How to modify the scheduling priority ?
2)What is the default nice value ?
3)What is the highest priority value ?
4)What is the lowest priority value ?
5)How to get the process details of user Qwest using pgrep ?
6)How to kill all the processes of user Qwest using pkill ?
7)How to get the virtual memory statistics information ?
8)How to get the IO statistics information ?
9) What is the equivalent command for top ?
10) How to get the top n processes ?
11)How to get the working directory of a process ?
12) How many ways we can back ground a job ?
13) How to fore ground a job ?
14) How to get the pid of background jobs ?
15)Why nohup is required ?
16) What is the default output file for nohup ?
17)Syntax of nohup command ?
18) How to run a script in back ground ?
19) Suppose one job ( fore ground job) is running on your console. Now you want to make the job to run in
back ground .What are the steps ?
20) What is the use of & ?
21) Will you able to kill a process owned by root ?
203
Job Scheduling
at
atq
atrm
batch
crontab
anacron
job schedulers
Control M
autosys
204
at,atq,atrm,batch
205
Example
1. To schedule the command from the terminal, enter a command similar to one of the following: If uuclean is in your current directory, enter:
at 5 pm Friday uuclean
<Ctrl-D>
Note: When entering a command name as the last item on the command line, a full path name must be given if the command is not in the current directory, and the at command will not accept
any arguments.
2. To run the uuclean command at 3:00 in the afternoon on the 24th of January, enter any one of the following commands:
3. To have a job reschedule itself, invoke the at command from within the shell procedure by including code similar to the following within the shell file:
at -l
at -r ctw.635677200.a
This cancels job ctw.635677200.a. Use the at -l command to list the job numbers assigned to your jobs.
206
Example
207
crontab
crontab Submits, edits, lists, or removes cron jobs.
minute 0 through 59
hour 0 through 23
day_of_month 1 through 31
month 1 through 12
weekday 0 through 6 for Sunday through Saturday
command shell command(s)
208
Examples:
1. To copy a file called mycronjobs into the /var/spool/cron/crontabs directory, enter the following:
crontab mycronjobs
The file will be copied as: /var/spool/cron/crontabs/<username> where <username> is your current user name.
2. To write the time to the console every hour on the hour, enter:
3. To run the calendar command at 6:30 a.m. every Monday, Wednesday, and Friday, enter:
30 6 * * 1,3,5 /usr/bin/calendar
4. To run the calendar command every day of the year at 6:30, enter the following:
30 6 * * * /usr/bin/calendar
5. To run a script called maintenance every day at midnight in August, enter the following:
0 0 * 8 * /u/harry/bin/maintenance
0 16 * 12 5 /usr/sbin/wall%HAPPY HOLIDAY!%Remember to
turn in your time card.
The text following the % (percent sign) defines the standard input to the wall command as: HAPPY HOLIDAY! Remember to turn in your time card.
209
Questions ??
210
Disk usage commands
df
du
bdf
quota
mount
umount
eject
211
Architecture of Unix File system
Formatted Disk
File system
SubDir SubDir
213
du,quota,mount,umount,eject
du - estimate file space usage
any user can mount the iso9660 file system found on his CDROM using the command
eject –t With this option the drive is given a CD-ROM tray close command. Not all devices
support this command.
214
Questions ??
215
Mailing commands/Utilities
- mail
- mailx
- uuencode
- sendmail
- pine
216
mail
mail - send and receive mail
-s Specify subject on command line (only the first argument after the -s flag is used
as a subject; be careful to quote subjects containing spaces.)
-c Send carbon copies to list of users.
-b Send blind carbon copies to list. List should be a comma-separated list of
names.
217
mailx
mailx - mailx - interactive message processing system
-s subject Set the Subject header field to subject. subject should be enclosed in quotes if it
contains embedded white space.
-b bcc Set the blind carbon copy list to bcc. Bcc should be enclosed in quotes if it contains
more than one name.
-c cc Set the carbon copy list to cc. cc should be enclosed in quotes if it contains more than
one name.
( cat body.txt
uuencode pic.jpg pic.jpg
) | mailx -s "subject" subhasis@Qwest.com
218
sendmail
MAILTO="subhasis@Qwest.com"
MAILFROM=" subhasis@Qwest.com "
echo 'Subject: *** DirB Statistics ***
From: '$MAILFROM'
To: '$MAILTO'
Daily Processing Details
-------------------------------------------------------
Eastern Reads :$Eastern
Western Reads :$Western
Central Reads :$Central
Total Reads :$TOTAL
-------------------------------------------------------
Thanks ,
Subhasis
'| /usr/sbin/sendmail $MAILTO
219
Questions ??
220
Networking commands
ifconfig
netstat
ping
ipcs
ipcrm
221
Ifconfig,netstat,ping,ipcs,ipcrm
ifconfig - configure a network interface / to check the ip address for interfaces
netstat - Print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships
-a, --all Show both listening and non-listening sockets.
ping - This command is used to check the network resources (hosts) are alive or not ?
-M shmkey removes the shared memory segment created with shmkey after the last detach is
performed.
-m shmid removes the shared memory segment identified by shmid after the last detach is performed.
-Q msgkey removes the message queue created with msgkey.
-q msgid removes the message queue identified by msgid.
-S semkey removes the semaphore created with semkey.
-s semid removes the semaphore identified by semid.
222
Example:
223
Questions ??
224
Printing commands
225
lp/lpr - submit a print job
lp and lpr submit the specified file, or standard input, to the printer daemon to be printed. Each
job is
given a unique request-id that can be used to follow or cancel the job while it’s in the queue.
Syntax
lp [options] filename
lpr [options] filename
Common Options:
lp lpr function
---------------------------------------------------------------------------------------------
-n number -#number number of copies
-t title -Ttitle title for job
-d destination -Pprinter printer name
-c (default) copy file to queue before
printing
(default) -s don’t copy file to queue
before printing
-o option additional options, e.g. nobanner
226
lpstat/lpq - check the status of a print job
You can check the status of your print job with lpstat or lpq.
Syntax
lpstat [options]
lpq [options] [job#] [username]
Common Options
lpstat lpq function
-d (defaults to lp) list system default
destination
-s summarize print status
-t print all status information
-u [login-ID-list] user list
-v list printers known to the
system
-p printer_dest -Pprinter_dest list status of printer, printer_dest
227
cancel/lprm - cancel a print job
228
pr - prepare files for printing
pr prints header and trailer information surrounding the formatted file. You can
specify the number of pages, lines per page, columns, line spacing, page width, etc.
to print, along with header and trailer information and how to treat <tab> characters.
Syntax
pr [options] file
Common Options :
+page_number start printing with page page_number of the formatted input file
-column number of columns
-a modify -column option to fill columns in round-robin order
-d double spacing
-e[char][gap] tab spacing
-h header_string header for each page
-l lines lines per page
-t don’t print the header and trailer on each page
-w width width of page
229
Questions ??
230
Arithmetic operations
bc
expr
(( ))
231
Scale:-
By default, bc performs truncated division.One have to set scale to the
number of digits of precision before performing any division.
$bc
If answer to division is greater than the value as
scale=2
dictated by the scale variable, then the value dictated
10/4 by the scale is ignored and the real value is shown.
2.50
^d
$
233
ibase and obase:-
By default, the input and output are interpreted as decimal values.But, if the
demand required input and/or output in different number system(binary,
hexadecimal), variables ibase and obase are set.
To convert binary input to decimal output:-
ibase=2
To convert decimal input(default) into binary output:-
obase=2
For hexadecimal systems, value ’16’ is used in ibase/obase variable.
234
Handling Variables:-
Variables can be used in bc mode and values can be assigned to them.
$bc
X=12 ; y=19
Z=x+y
Z
31
235
Square Root of a Number
Syntax : sqrt ( x )
Example :
$bc
Sqrt ( 4 )
2
Length of a Number
Syntax : length ( x )
Example :
$bc
length ( 1234.5678 )
8
236
Trigonometric Functions
To use trigonometric functions of bc, one have to include math library.
For that , issue the following command from Os prompt:-
$ bc –l
Various trigonometric functions available with ‘bc’ are:-
s(x) sine
c(x) cosine
e(x) exponential
l(x) log
237
String handling
239
factor
$factor 15 $factor 18
15 18
2
3
3
5
3
$
$
240
primes
Shows all prime numbers between integers <lower value> and <upper value>.
If upper value is not provided, it is considered to be 2,147,483,647.
$primes 0 10
2
3
5
7
$
241
units
242
Use (( ))
$ A=5;B=12
$ echo $(( A + B ))
17
$ echo $(( $A + $B ))
17
$ ( echo scale=3 ;echo 5 / 2 )|bc
2.500
$ echo "2.3 + 4.5" |bc
6.8
$ echo "5.0 / 2.1" |bc
2
$ ( echo scale=3 ;echo 5.0 / 2.1 )|bc
2.380
$ expr 2.3 + 4.5
expr: non-numeric argument
$ expr 2 + 4
6
243
Questions ??
244
Useful commands:
- telnet
- ssh
- scp
- sftp
- ftp
- Automate SSH login using public key .
- rlogin
- remsh
- sum
- cksum
245
Useful commands:
246
Questions ???
247
Misc commands :
-getent
-useradd
-userdel
-usermod
-groupadd
-groupdel
-groupmod
-chage
-basename
-which
-whatis
-whereis
-alias
-man
-info
-history
-file
-type
-script
-tee
-pstree
-shutdown
-poweroff
-reboot
248
Misc commands :
database is the name of the database to be examined. This can be passwd, group, hosts,
ipnodes, services, protocols, ethers, project, networks, or netmasks.
249
Misc commands :
chage - change user password expiry information
Example : whatis ls
whereis - locate the binary, source, and manual page files for a command
Example : which ls
250
Misc commands :
Example : type ls
251
Misc commands :
script - make typescript of terminal session
After starting the scripting, user continues with his job. All the commands he uses, their output and error
messages are stored for later view.
When the user exits from the scripting(writing : exit from OS prompt), the script file is saved and a message is
shown:-
252
tput : Controls screen display
Options Significance
tput clear Clears the screen
tput cup <r> <c> Moves cursor to row <r> and column <c>
tput bold Bold display
tput blink Blink display
tput rev Reverse display
253
Commands Significance
ls –t Sorts files by modification time – the file modified most recently comes at
the top
ls –ut Sorts files by access time
ls –r Sorts file in reverse order
ls –ltr Shows long listing of files with their attributes, sorted in reverse order by
access time(most recently edited file comes last in the list)
ls –i Shows inode number of a file
ls *.ksh Shows the name of all files with ‘.ksh’ at the end of their name
ls d*.sh Lists all files starting with ‘d’ and ending with ‘.sh’ in their name
ls d?l* Lists all files with first letter as ‘d’ and third letter as ‘l’
ls [!aeiou]* Shows the files with names not starting with vowels
254
Thank You !!!!
Any Questions Mail me
Subhasis.samantaray@centurylink.com
subhasis.samantaray@gmail.com