You are on page 1of 125

Linux Commands

Introduction: Unix is the first operating system in the world, developed by Kem Thompson and
Dennis Ritchie in 1969 at Bell Lab by AT&T Company.
FSF: Free software foundation organization, they start a project by name GNU. The main aim of
this project is to develop such a O.S. that can run on any platform. In 1991, a student Linux
Tarvalds developed a kernel named Linus Kernel plus GNU application called Linux O.S.
Linux is an open source technology. Different companies that provide Linux in market are
Redhat, SuSe, Mandrake, Turbo, Knoppix, Ubuntu etc.
Linux Features:

Linux is the fastest operating system in the world. It runs 2 to 3 times faster than windows O.S.

Linux is the very secured O.S. Because there is no any problem of virus.

Linux file format is text format and windows file format is binary format.

Linux is very reliable operating system because kernel of Linux is very stable as compare
to windows kernel not crashed easily.

The linux kernel is very small; it can store in floppy disk.

Linux sues the x-windows system which is advanced network windowing system. Using
this system we can display output of any workstation monitor attached in the network.
Linux Advantages:

Virus Proof

Crash Proof

Economical

Multiuser, Multi desktop and multitasking

What is the shell?


The shell in Linux is the interface through which you will carry out most of your work. While it
seems in outward appearance to be unsophisticated, a lot of power is available to the shell user, by its
ability to combine commands.
Available shells in Linux
A number of different shells are available in Linux, which cater for different needs. At a basic
level, they all allow you to enter commands, and redirect the output of the commands to the
appropriate place, be it a file, or your terminal.
There are two major schools of shells; the sh family, and the csh family. When only using the shell
as an interactive tool, they are all reasonably similar, with some shells providing facilities to make
interactive use easier (such as aliases, programmable command completion and histories). However,
when using the shell to write scripts, there is a very large difference between the different families.

Jitendra Rathi, Lecturer, Engineering College Bikaner Page No. 1


Some of the common types of shells are listed below.
Linux shells
Name Features Startup Files
sh Basic shell and always available .profile
bash Completion, aliasing, history and almost .bash_profile
always available
.bashrc
.inputrc
ksh Completion, aliasing, history and Non-standard .profile
zsh Competion, aliasing, history and Non-standard .zshenv
.zprofile
.zshrc
.zlogin
csh Completion, aliasing, history and almost .cshrc
always available
.login
tcsh Completion, aliasing, history and almost .tcshrc
always available
.login

Linux Filesystem:
The filesystem in Linux can be seen as a tree, or hierarchical structure. Everything starts with the
root directory, also known as slash and /.
Example Linux filesystem layout
/

/bin /etc /home /boot /dev /temp /opt /mnt /usr

/home/jitendra /home/rajesh /usr/local /usr/bin

/home/jitendra/projects /home/rajesh/projects

DOS v/s Linux

Jitendra Rathi, Lecturer, Engineering College Bikaner Page No. 2


If you are able to navigate through MS-DOS will be able to pick up on the navigation of LINUX in
the following chart we have listed several of the various similarities of DOS and LINUX.

DOS LINUX
attrib chmod
backup tar, gzip, bzip2, zip
dir ls
cls clear
copy cp
del rm
deltree rm R or rmdir
edit vi, vim, pico
format fdformat, mount, umount
move / rename mv
type less <file>
cd cd, chdir
more < file more file
md mkdir
win startx or xterm

ls: Display all the files and directories present in the current directory.

Usages Syntax-
ls [options][Files]

Options:-
l :- Display all the files, directories, their mode. Number of links, owner of the file, group of
the owner, file size, modified date and time and filename.

-t : Display files list by last modification time


-a : Display all the files along with hidden files.
-d : Display directory files instead of contents.
-p : Puts a (/) slash sign at the end of each directory.
-u : Display files list by last access time.
-i : Display files inode information.
-r : Display files list in reverse order
-x : Display multi columnar output
-S : Display largest file first.
-ltr : Display files order by date
-lSr : List files order by file size.

[jitendrac@ntserver ~]$ ls
-l total 44
drwxr-xr-x 2 govindc staff 4096 Dec 22 04:47 documents
-rw-r--r-- 1 govindc staff 558 Jan 1 07:34 ipaddr.pl
-rw-r--r-- 1 govindc staff 291 Jan 1 08:15 stars.c
lrwxrwxrwx 1 govindc staff 8 Jan 1 06:14 t -> tutorial
drwxr-xr-x 3 govindc staff 4096 Jan 1 06:24 tutorial
-rw-r--r-- 1 govindc staff 34 Jan 2 05:09 user.sh
[govindc@ntserver ~]$
Jitendra Rathi, Lecturer, Engineering College Bikaner Page No. 3
$ls l | more :- Display all the commands page wise
[jitendra@ntserver ~]$ ls -l |
more total 8484
-rw-rw-r-- 1 jitendra jitendra 312 Jan 15 04:42 addstring.c
-rwxrwxr-x 1 jitendra jitendra 5008 Jan 15 04:42 a.out
-rw-rw-r-- 1 jitendra jitendra 8388608 Jan 4 04:25 backup.tar.gz
drwx------ 2 jitendra jitendra 4096 Jan 3 06:08 ccna
-rw-r--r-- 1 jitendra jitendra 621 Apr 20 09:00 client.pl
-rw-r--r-- 1 jitendra jitendra 443 Apr 15 05:47 c.pl
-rw-rw-r-- 1 jitendra jitendra 401 Jan 15 04:24 distance.c
-rw-r--r-- 1 jitendra jitendra 361 Jan 15 05:14 factorial.c
-rw-rw-r-- 1 jitendra jitendra 651 Jan 12 05:32 filehandling.c
-rw-rw-r-- 1 jitendra jitendra 152 Feb 15 12:21 file.pl
-rw-r--r-- 1 jitendra jitendra 2153 Jan 15 05:14 futurevalue.c
--More--

$ls a : Display files list including hidden (. dot files)


[jitendra@ntserver ~]$ ls -a
. .bash_logout .canna .gtkrc stars.c user.sh .zshrc
.. .bash_profile documents ipaddr.pl t .viminfo
.bash_history .bashrc .emacs .kde tutorial .xemacs
[govindc@ntserver ~]$

$ls li : Display files list with inode


number. [jitendra@ntserver ~]$ ls -li
total 44
24838442 drwxr-xr-x 2 govindc staff 4096 Dec 22 04:47 documents
24838443 -rw-r--r-- 1 govindc staff 558 Jan 1 07:34 ipaddr.pl
24838441 -rw-r--r-- 1 govindc staff 291 Jan 1 08:15 stars.c
24838421 lrwxrwxrwx 1 govindc staff 8 Jan 1 06:14 t -> tutorial
24838450 drwxr-xr-x 3 govindc staff 4096 Jan 1 06:24 tutorial
24838445 -rw-r--r-- 1 govindc staff 34 Jan 2 05:09 user.sh
[jitendra@ntserver ~]$
$cd <directory name> :- Change the current working directory to specified directory, relative to
the current location.
$cd.. :- Goto the parent directory of the current directory
$cd ~ or f9 key :- Move to the users home directory which is /home/username. The ~
indicates the users home directory.
$cd / :- Directly go into root directory
$cd /bin :- Change directory to /bin as a working directory

$clear :- Clears the screen


$mkdir <directory name> :- Create a new directory
$mkdir <dirname> <dirname> <dirname> : Create Multiple Directories at the same time.

$rmdir <Directory Name> :- Remove a directory but does not delete all those directories which
are not empty.

Jitendra Rathi, Lecturer, Engineering College Bikaner Page No. 4


$rmdir cs/language cs/package cs : Remove multiple directories at the same time.

$pwd :- Display path of present working directory

$logout or ^d :- for logout the current session

$ prompt :- Normal User


# prompt :- Supervisor or Root user

$su :- It is use to gain super user privilege, it asks the root


password. [jitendra@ntserver ~]$ su
Password:
[root@ntserver govindc]# exit
exit
[jitendra@ntserver ~]$
$more filename : Display file contents Page wise (Press q to quit)
$more file1 file2 file3 : Display all files page wise

Note: The file .profile contains set of instructions that are performed when a user logs in. (It is
similar to Autoexec.bat of DOS)

$man <UNIX Command> :- For Help and press <q> to quit from help
$man shutdown :- Help of Shutdown Command
$man ls l :- Help of a particular command

History: The history command is use to manipulate the previously entered commands history list.
It performs several operations related to previously executed commands recorted in the history list
and these recorded commands referred to as en event. All the events are numbered starting from 1
with history command. We can specify event number in a positive form or in a negative form.
Event 0 (zero) represents the current event and -1 represents the previous event, -2 represents one
before that and so on.

Usages syntax:
$history [options] arg1,arg2,.

$history :- Display the list of commands that you have entered before.
$history 10 :- Display last entered 10 commands. If you enter history 20 instead of
history 10 then displays last entered 20 commands.

Note:- By default history stores last 1000 commands which you have run. If you want to change
then open #vi /etc/profile and set HISTSIZE = 2000

$history clear: Deletes the entire history or use e option instead of clear.

Searching a command from history (ctrl+r) : To execute a long command which is previously
executed then search that command from history by using ctrl+r keys. To search tar command
from history then press ctrl+r at command prompt and type tar, then prompt display as follows:

Jitendra Rathi, Lecturer, Engineering College Bikaner Page No. 5


[jitendrac@ntserver ~]$
(reverse-i-search)`tar`: tar zcvf backup.tar.gz. /home

There after press enter key to execute the command or press left or right arrow keys to modify
the command from history and then execute.

Execute previously entered command quickly: There are many ways to execute the previously
entered command quickly without typing the command.
1. Type !! and press enter key to execute just previous command again.
2. Press up arrow key and press enter key
3. Type !-1 and press enter key.
4. Press ctrl+p and press enter key. (^p displays previous command at prompt).

To execute any command from history quickly then type ! and some keywords of the command
and then press enter to executes the command. i.e. to execute grep command from history then
type !gre and press enter.

Echo: The echo command prints the given input string to standard output device. The default
behavior of echo is, prints the string on to standard output and move cursor into newline.

Usages Syntax:
$echo [options]
[string]

Options:
-n Do not move cursor into new
line.
-e Supports escape sequence characters in bash shell. By default bash shell does not support
escape
sequence characters.

Following escape sequence characters used with echo


command.
\a alert (BELL)
\\ backslash
\b backspace
\c suppress trailing newline character
\f form feed
\n newline
\r carriage return
\t horizontal tab
\v vertical tab

$echo $HOME :- The HOME variable is use to find out the name of your
home directory.
[govindc@ntserver ~]$ echo $HOME
/home/staff/govindc
[govindc@ntserver ~]$

How to make a Dos command in Linux


$cls() : Define a Function to make linux equivalent
Jitendra Rathi, Lecturer, Engineering College Bikaner Page No. 6
command.
>{
>clear

Jitendra Rathi, Lecturer, Engineering College Bikaner Page No. 7


>}

$cls :- Clears the screen

$date :- Display current system date and time


+%m : Display only Month Number
+%h : Display Month Name
+%Y : Display Year (in yyyy format)
+%d : Day of month (01..31)
+%e : Day of month, blank padded (1..31)

$date +%m or $date +%h %m


[jitendra@ntserver ~]$ date
Sat Jun 5 12:32:50 IST 2010
[jitendra@ntserver ~]$ date +
%m
06
[jitendra@ntserver ~]$ date +"%h %m"
Jun 06
[jitendra@ntserver ~]$ date +%F
2010-06-05
[jitendra@ntserver ~]$ date +%y-%m-%d
10-06-05
[jitendra@ntserver ~]
$
$bc : Basic Calculator, it is used for command line calculator. By using we can do
mathematical calculations. (to end of bc press Ctrl+D).

Syntax:

$bc [options]
Use the math library functions and initialize scale to 20, instead of default
-l value zero.
filename Specify the file name that contains the basic calculator commands to be calculated.
-q Do not print initial banner
-v Prints bc command version number and then exit.

[jitendra@ntserver ~]$
bc bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation,
Inc. This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
10 + 5
15
10*10
100
7/2
3
scale=2
7/2
3.50
Jitendra Rathi, Lecturer, Engineering College Bikaner Page No. 8
Note: By default bc command cant display decimal places

scale=2 : Specify number of decimal places.


ibase=2 : Converts Binary Number into Decimal Number.
obase=2 : Converts Decimal Number into Binary Number.
obase=16 : Converts Decimal Number into Hexadecimal Number.

[jitendra@ntserver ~]$ bc
-q ibase=2
11001010
202
[jitendra@ntserver ~]$ bc
-q obase=2
14
1110
[jitendra@ntserver ~]$ bc
-q obase=16
14
E
[jitendra@ntserver ~]$

$cal :- Display calendar of current month and


year. Usages syntax:

cal [options] [month]

[year] Options:
-s Display Sunday as first column.
-m Display Monday as first column.
-3 Display previous/current/next months calendar.
-y Display 12 months calendar of current year.
[jitendra@ntserver ~]$ cal
June 2010
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

[jitendra@ntserver ~]$ cal -3 11 2009


October 2009 November 2009 December 2009
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 1 2 3 4 5 6 7 1 2 3 4 5
4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12
11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19
18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26
25 26Here
Note: 27 28
cal29command
30 31 29displays
30 27 28
calendar of29 30Nov.
Oct. 31 and Dec. 2009. \

[jitendra@ntserver ~]$

Jitendra Rathi, Lecturer, Engineering College Bikaner Page No. 9


$cal 09 1752 :- Display calendar of specified month and years (09 = Month No. & 1752 = Year)

[jitendra@ntserver ~]$ cal 09 1752 [jitendra@ntserver ~]$ cal -s [jitendra@ntserver ~]$ cal -m
September 1752 June 2010 June 2010
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Mo Tu We Th Fr Sa Su
1 2 14 15 16 1 2 3 4 5 1 2 3 4 5 6
17 18 19 20 21 22 23 6 7 8 9 10 11 12 7 8 9 10 11 12 13
24 25 26 27 28 29 30 13 14 15 16 17 18 19 14 15 16 17 18 19 20
20 21 22 23 24 25 26 21 22 23 24 25 26 27
27 28 29 30 28 29 30
[jitendra@ntserver ~]$ [jitendra@ntserver ~]$ [jitendra@ntserver ~]$

$info <Linux Command> :- Display help of a command. (Use Spacebar, Enter


Key, PgUp PgDn keys for scrolling in help)

$cat > filename :- Create a new file (To save the file press ^d)
$cat filename :- Display the contents of a file (It is same as DOS TYPE Command)
$cat <Source file Name> > <Target File Name> :- Copy the contents of source file into
Target file. If target is already exist then overwrite Target file
without asking any question.
$cat <Source File Name> >> <Target file Name> :- Append source file contents in
Target file.
$cat a* > new.txt :- Copy all the files which have the first character is <a > into a
new file new.txt
$cat first.txt second.txt >> my.txt :- Copy the contents of First.txt and Second.txt
file into a new file my.txt

rm : The "rm" command is used for deleting a file or directory (folder). The command name
"rm" is derived from "remove".

Usages syntax:
$rm [options] [files]

Options:
-i interactive delete, display prompt before deletion so that we can delete selected files.
-r, -R Recursively delete all the files and directories from current directory to lower most level of sub
directories.
-v verbose mode, display what is being done.
-f Remove all files including write-protected also without prompting the user

$rm filename :Delete the specified filename.


$rm file1 file2 file3 : Delete list of files
$rm * : Delete all Files
i : Delete selected file
$rm i file1 file2 file3 : Ask permission (Y/N) before deletion so that we can
delete selected files.
Note: rm cant delete all those files which are write protected, but display prompt for removing

Jitendra Rathi, Lecturer, Engineering College Bikaner Page No. 10


$rm rf *

mv : Renaming a filename or move it from one directory to another directory


$mv oldfilename newfilename : Renaming a File Name (Also use for Renaming a
Directory Name)
$mv oldfilename newfilename oldfilename newfilename : For multiple file Renamings

Note: mv command also use for moving files from one directory to another
directory

$mv f1.txt f2.txt cs : Move files into cs directory.

$who :- Display all the users which are currently log on in particular machine
-H : Display with header option
-u : Display more detail

[jitendra@ntserver ~]$ who


jitendra pts/0 Jun 5 12:32 (jitendra-pc)
govindc pts/1 Jun 5 12:51 (jitendra-
pc) [jitendra@ntserver ~]$

$who Hu
[jitendra@ntserver ~]$ who -Hu
NAME LINE TIME IDLE PID COMMENT
jitendra pts/0 Jun 5 12:32 . 18879 (jitendra-
pc) govindc pts/1 Jun 5 12:51 . 18957
(jitendra-pc) [jitendra@ntserver ~]$

$who T :- Display all the users information they can receive or cant receive your
messages. The + sing indicates for Receive and sign indicates for
Cant receive any message.

[jitendra@ntserver ~]$ who -T


$whoami + pts/0 :-Jun
jitendra 5 12:32
Display (jitendra-pc)
current login status
govindc + pts/1 Jun 5 12:51 (gitendra-pc)
[[jitendra@
jitendra@nnttsseerrvveerr ~]$
~]$
whoami jitendra
[jitendra@ntserver ~]$
$write <username> :- Send a message to a particular user (Press ^d to Finish Message)
[jitendra@ntserver ~]$ who
jitendra pts/0 Jun 5 12:32 (jitendra-pc) govindc pts/1
Jun 5 12:51 (jitendra-pc) [jitendra@ntserver
~]$ write govindc
Hello
are you busy or can you give me 5 minutes right now
[jitendra@ntserver ~]$
Note: When a user send a message then on the receiver side its looks like:
[govindc@ntserver ~]$ [jitendra@ntserver ~]$
Message from jitendra@ntserver on pts/0 at
12:59 ... Hello
are you busy or can you give me 5 minutes right now
EOF
$write user1 user2 usern :- Send messages to multiple users

$mesg y/n :- y = Accept messages from other users


n = Cant receive any message from other users

[jitendra@ntserver ~]$ write govindc


write: govindc has messages disabled
[jitendra@ntserver ~]$

$fortune :- Display Jocks randomly.

$cp <Source File> <Target File> :- Copy a file


Copy a Directory along with all the subdirectories and files.
$cp r <Source DirName> <Target DirName>
$cp rf <Source DirName> <Target DirName>

The f Switch is use to forcefully copy, it removes existing files on destination path. We also use
R
instead of r option.

$cp i myfile yourfile : If target file is already exist then asks for overwriting.

Note:- The -p (preserve mode) remains files ownership, group, permissions, timestamps as it is.

$ ls l Owner Group

-rw-r--r-- 1 root root 8 Jul 9 08:29 abc


drwx------ 3 root root 1024 Jul 9 08:01 Desktop

Links/Pointers
The First byte Show Property d = directory
The next Three Bytes rw- Shows User
Rights The next Three Bytes rShows
Group Right And Last Three Bytes rshows
others

r-- r-- r-- =4


100 100 100
-w - - w- -w- =2
010 010 010

6 6 4 4= r = read
110 110 100 2=w = write
rw- rw- r- - 1=x = execute
user group other
Numeric Permissio ns:
CHMOD can also to attributed by using Numeric Permissions:

400 read by owner


040 read by group
004 read by anybody (other)
200 write by owner
020 write by group
002 write by anybody
100 execute by owner
010 execute by group
001 execute by anybody

$chmod 755 a1.txt

Which would be the following 400+040+004+200+020+100+010+001 = 775

factor : Calculate and display the prime factors of number n. If n is not specified, numbers are read
from stdin, separated by commas, spaces, or tabs. This may take a very long time for numbers that
are the product of two primes.

Usages: $factor [options] n

[root@proxy ~]# factor 10 20 30


10: 2 5
20: 2 2 5
30: 2 3 5
[root@proxy ~]# factor 12
12: 2 2 3
[root@proxy ~]#

pg : Used to display data one page (screenful) at a time. The command can take a number
of filenames as arguments.

pg [option] [filename] [filename2]

.. Options:
-number An integer specifying the size (in lines) of the window that pg is to use instead
of the default. (On a terminal containing 24 lines, the default window size is
23).
-p string pg uses string as the prompt. If the prompt string contains a %d, the first
occurrence of %d in the prompt will be replaced by the current page number when
the prompt
is issued. The default prompt string is ``:''.
-c Home the cursor and clear the screen before displaying each page. This option is
ignored if clear_screen is not defined for this terminal type in the terminfo(4)
data base.
-e pg does not pause at the end of each file.
-f Normally, pg splits lines longer than the screen width, but some sequences of
characters in the text being displayed (for instance, escape sequences for
underlining) generate undesirable results. The -f option inhibits pg from
splitting lines.
-n Normally, commands must be terminated by a <new line> character. This
option causes an automatic end of command as soon as a command letter is
entered
-r Restricted mode. The shell escape is disallowed. pg prints an error message
but does not exit.
-s pg prints all messages and prompts in the standard output mode (usually
inverse video).
+linenumber Start up at line number.
|/pattern/ Start up at the first line containing the regular expression pattern.
filename A path name of a text file to be displayed. If no filename is given, or if it is -,
the standard input is read.

$file <filename> :- Display file status (There are basically three types of files
ordinary, directory and device file).

$cmp file1 file2 : Compare two file are identical or not.


-l : Give a detailed list of the byte no. and the differing bytes in octal for each character
that differ in both files.
$cmp -l a1.txt a2.txt

$comm file1 file2 : Display all the data which are common or uncommon.

$diff file1 file2 : Display the file differences.

$lpr filename : Print a file on printer


$lpr -t Engineering College Bikaner filename : Print Title on First Page
-k<no> : Specify no. of copies to be print
-m<Mailid> : Mail message to specified mail id
$lpr k3 m jitendra@ecb.ac. in a1.txt : Print 3 copies and also mail document.

$cancel -p<printer name> : To cancel the printing.

$vi test.c : Create a C Program


{
printf(\n Hello World\n);
}

$cc test.c o test.out :- for compiling a C Program

$./test.out :- To execute the program

Note : To enter text in vi editor just press i.


vi Text Editor
vi is the standard Linux text editor that can be used to create and modify text files. Vi usages .exrc file to
to change the default behavior. This file (.exrc) contains many ex Mode commands which are available in
every session. Vi reads the .exrc file which is available into the home directory, if this does not exist then
create new one or copy from different location into $HOME/.exrc. Linux also provides improved version
of vi named as vim. Vim usages .vimrc file instead of .exrc file which is also available into
$HOME/.vimrc location.

The vi editor has three modes, command mode, insert/text mode and Ex Mode/.

1. Command mode: This is the default mode. When we open an existing file or create a new one then
vi automatically goes into this mode.
2. Insert/Text Mode: Text is inserted into the document. This mode is invoked by pressing the i
(inserts before cursor position), I (Inserts at the beginning of the line), a (append after cursor
position), A (appends at the end of the line), o (open new line after current line) or O (Open a new
line above current line) commands. The ESC key ends insert mode and returns you to command
mode
3. Ex Mode or Escape Colon Mode: Ex Mode opens a prompt on the last line. To enter into Ex
Mode from command mode by pressing the : (colon sign) which puts the command line entry at
the foot of the screen.

Starting vi: At shell prompt type vi [FILENAME] and then press [ENTER] key to starts the vi editor.
If the FILENAME does not exist, a blank screen with just a cursor at the top followed by tildes
(~) in the first column.
If the FILENAME already exists then open the file contents on screen.
The status line at the bottom of the screen shows error messages and also provides feedback
information include filename.

Exiting from vi: To exit from vi you must be command mode, if not then press [ESC] key and then go into
Ex Mode by pressing : (colon) key.

Following commands are used into Ex-Mode

:wq Save file onto disk and quit from vi.


:x Save file and quit from vi.
:q Exit from vi if file has not been changed.
:q! Quit from file without saving the changes.
:w Write to the file and continue editing
:w filename Save file contents into the specified filename. (It is same as :1,$w filename)
: .w filename Save current line to the specified filename.
: .,$w filename Save text from current line to end of file into specified filename
th
:10w filename Save 10 line into specified filename.
th th
:5,15w filename Save lines from 5 to 15 into specified filename
Note: If specified filename already exists with w command the vi displays warning message to use w!
filename to overwrite existing file.
ZZ Write to the file in quit from vi
Cursor movement: The following keys are used in command mode to move current cursor position.

h k j l

Keystrokes Action
h Move cursor one character left k
Move cursor one line up
10k Move cursor ten lines up
j Move cursor one line down
l Move cursor one character right w
Move one word right
5w Move cursor ahead 5 words
b Move cursor back a word at a time
B Move cursor back a word at time
5b Move cursor back 5 words
e Move cursor to end of word
5e Move cursor ahead to the end of the 5th word
0(zero) Move cursor to beginning of line
$ Move cursor to end of line
% Move cursor to the matching bracket. Place cursor on {}[]() and type "%".
+/- Move cursor down/up in first column
H Move to the first line on the screen
M Move to the middle line on the screen
L Move to the last line on the screen.
:fx Moves to the cursor to the specified character x in the forward direction.
:Fx Moves to the cursor to the specified character x in the backward direction.
;tx Move cursor just before the specified character x in the forward direction.
:Tx Moves the cursor just after the specified character x in the backward direction. G
Move cursor to the beginning of the last line in the file
#G Move cursor to the beginning of the #th line in the file
Ctrl+d Scroll down one half of a page
Ctrl+u Scroll up one half of a page. Ctrl+f
Scroll forward one page Ctrl+b
Scroll backward one page
'. Move cursor to previously modified line.
a Move cursor to line mark "a" generated by marking with keystroke "ma"
A Move cursor to line mark "a" (global between buffers) generated by marking with
keystroke "mA"
] Move cursor to next lower case mark.
[ Move cursor to previous lower case mark.

Moving cursor by sentences: In vi editor a sentence ends with ! or .(period) or ?. These characters appear
in the middle of a sentence followed by blanks.
( Move cursor to the beginning of the current sentence.
) Move cursor to the beginning of the next sentence.

Moving cursor by paragraphs: Positioning the cursor by paragraphs then first make sure each
paragraph begins after a blank line. The blank line indicates to starts a new paragraph.
{ Move cursor to the beginning of the paragraph.
} Move cursor to the beginning to the next paragraph.
Deleting Text: To delete text from vi editor then vi command line mode provides the
following commands to delete text to word speed up.

x Delete character under cursor position and the text on the right hand side shifted to
left to fill up space. If cursor positioned at the end of line then delete character from
left.
5x Repeat factor, it delete five character from right hand side and text shifted to left.
X Delete character before cursor position.
dd Delete the entire line where cursor is positioned.
10dd Deletes current line and below nine lines.
#dd Delete # number of lines from cursor position.
Ctrl+w Delete entire word from cursor position to
left. D or d$ Delete from cursor position to end of line.
dw Delete a word from cursor position.
4dw Delete 4 Words

Repeating Character: To repeat a character multiple times then in the insert mode type a
character i.e. /* and then press ESC key and then enter 60a* (repeat 60 times * and a = append
into file) and press ESC key then you will 60 *s displays.
/************************************************************

Note: A superb text completion feature is available in vim i.e. press c then press ^p to display all
the words available starting from c with header file. To view a list of backwards then press ^n.

Escape to Linux Shell (sh and ^z) : There are two ways to temporarily exit from vi editor.
a) In Ex Mode type :sh[ENTER] then immediately return to shell prompt. To again return into
vi editor press CTRL+d or type exit.
b) Press CTRL+z to suspend job vi editor and return to shell prompt. There after use fg
command to return to foreground into vi editor.

Joining Text (J) : to remove new line character between two or more lines to pull up the lines
below it. i.e. 5J : join five lines into single line.

Operators: - The strongest feature of is editor is that the combination of command mode. The
operator are as :-
d- Delete y- yank (copy)
c- Change !- filter
Note: - An operator above cannot perform any function but works with a command or used itself
twice. When we use operators twice then only work on current line. e.g. dd deletes the entire line.

Deleting text (x):- To delete the certain portion of text from file then use operator with a command.
e.g. d$ Delete from cursor position to end of line
dw Deletes the entire word
10dw Deletes 10 words from current cursor position to forward
dG direction
10dd Deletes ten
from cursor
lines position
from currenttoposition
end of file
to forward of direction.

Paste deleted text (P and P):- To place the deleted text at different location then P and P command
are used. The P pastes the deleted text below or after the cursor position and P pastes the deleted text
above or before the cursor position.
Copying/Yanking text (y):- The y operator yanks/copies text and it works in the same way as operator
d works, and the P or P command are used to pastes copied text at current cursor position. E.g.
10yy yank/copy 10 lines from cursor position to forward direction and then move cursor at appropriate
place and then press 8 or P command to paste the copied text.

Changing text (c):- To change the text then (c) operators is used. It works same as (d) operator but the
only difference is that when use (c) operator then we automatically moves from command mode into input
mode. e.g. cc change(or delete) entire line and also goes into input mode, to again go into command
mode, press [Esc] key.

c$ or C: - change text from cursor position to end of


line.
10cc:- change ten lines in forward direction c/Engineering college Bikaner/[Enter] change all text
starting
from current cursor position to first match of specified pattern(Engineering college
Bikaner).

Filtering text (!):- To filtering text within vi editor then (!) filter operator is used, it requires three things
(a) Move cursor to beginning of the position (b) Moving cursor to ending of the location using (G)
command
(c) A Linux command which act on the beginning & ending of the
location.

Example:

! 1G: - Move cursor to beginning of file.


! G Sort: Sorts the entire file.
Note: - We can also use (!) filter operator in ex
mode.
th th
: 5, 25! Sorts [Enter] Sorts lines from 5 to 25 some combination of command and operator.

Working with Multiple files :- The ex Mode provides the facilities to handle multiple files. This feature
is not provided by command mode. The :e command is use to works with multiple files.

Example:
:e matrix.c :- Temporarily leaves the current file and opens matrix.c.
:e# or [CTRL+n] :- Switch between files.

Opening multiple files :- vi provides the facility to open multiple files at the same time and it loads first
file contents into the buffer.

Example:
$vi first.c second.c third.c : Open Three files and load first.c file contents into buffer.

:n : Switch into next file without leaving the editor.


:rew : Rewinding the first file. At any stage we can move back to first file.

Note :- To switch between files n editor displays warning message to save data before leaning
it.
:e! : Ignore all unsaved data. It is same as :q command we can also use :n! or :rew!
to discard changes into current file and switch into another file.
Inserting file & command output into existing file:- To inserts the contents of a file at certain
location into currently opened file then in exmode (:r) command is used.
:r my.txt : Inserts my.txt file at cursor position.
:r !ls -l : Inserts ls -l command output into file.
Note:- To switch between files then unsaved text is deleted so that use : set auto write or :set aw
command to save automatically while switching between files.
Splitting window:- vi editor provides the facility to split a window into multiple windows. A
window can be empty windows or split a same file into separate windows.
:sp[Enter] To split existing window into two windows.
:new[Enter] Open a new blank window.
Note: - The CTRL+W is use to switch between windows and CTRL-W+ is use to increase the size
of current window and CTRL-W- is use to decrease the size of current window.
:on : Make current window in full screen & remove all other window.
Note:- :q is use to quit from current window and close it and :qa quit from all windows without
saving.
Some ex Mode commands examples to handling files.
:xa : Exit from all windows after saving
:r my:txt : Inserts my.txt contents below current line.
:r !head -3 my.txt : Inserts first 3 lines from my.txt below current line.
:e my.txt : Append buffered text into my.txt
:e! my.txt : Without save open file my.txt
:e! : Ignore all unsaved data and loads last saved text.
:e# : Returns to editing most recently edited file.
:n : Edits next file (if more than one files are opened
:rew : Rewind file list to starts editing from first file.

Named Buffers: By default vi editor stores the deleted text into an unnamed buffer so that we can
use only one buffer at a time and when we moving text from one file into another (using :e
filename), The contents of the default buffer automatically lost. To overcome this problem vi
provides 26 special named buffers named from a to z. To use named buffers then (double quote)
and buffer name is used.
Example:
a5yy : Copies 5 lines into buffer a.
b20yy :Copies 20 lines into buffer b.
ap : Paste text from buffer a at cursor position
Note: If a named buffer already contains text into the buffer then vi overwrite the existing contents.
vi usages uppercase letter to append text into existing buffer. e.g. B20yy instead of b20yy.
Example:
c20yy : Copy 20 lines into named buffer c.
:e newfile.c : Switch into newfile.c
G : Move cursor at bottom of file
cp : Paste text 20 lines from named buffer c.

Undo multiple deletions using numbered buffers: The undo command (u) only undoing the last
editing section. Vi also provides nine numbered buffers (1 to 9) to restore last nine complete
deletions. The most deleted text stored into buffer number 1 and the next-most deletion into buffer
number 2 and so on. So these buffers are accessed by using (double quote) and buffer number.
Example:

1p : Restore recently deleted text.


2p : Restore previously deleted text.

Note: The numbered buffer only works for entire line, does not work for partial line or words. i.e.
5dw, it deletes five words and cant possible to restore five words using numbered buffers.

Dot (.) command to restore previous deleted line: Generally the dot (.) command is to use to repeat
the previously entered command but it behaves differently when used with numbered buffers. Every
time when it is pressed, it steps one by one.

Example:
st th
1pu.u.u. : Restores buffer contents from 1 buffer to 4 buffer.

Entering Control Character [ctrl-v]: When we write shell script and send some escape sequence
character to terminal or printer then we requires control characters. Vi usages ctrl-v to precede
control character. For example to enter [ctrl-m], then first press [ctrl-v] and then press [ctrl-m] then
we will see on screen like:
^M : Here ^M only a single character.

Note: If we put ^ (caret) M then both are different-different characters. So that to combine
both characters into a single character then we require control character.

Search a Character: vi provides the facility to search a text within current line using the f and t
keys. The f key puts the cursor onto fist match of character within the current line in forward
direction and t key also works same as f but t puts the cursor before a character of first match of the
character into current line.

The T and F key works in opposite direction as f and t key works.

To repeat the same character then ; and , keys are used. The ; repeats the search pattern in same
direction as f and t key works and , key works in opposite direction along which previous search
was made with f and t keys.

Labeling Text Positions: vi provides the facility to mark up to 26 positions to moving cursor
position faster (labeled as a to z). To mark the text then m command is used and to locate the marked
text then
(single quote) command is used.
Example:
th
First move cursor at appropriate place i.e. 10G, Move cursor at 10
line.

ma Mark with label name a


th
50G Move cursor at 50 line of the
file. mb Mark location with label
name b.
a Move cursor at marked location
a
b Move cursor at marked location
b

Note: vi also provides doubled (single quote) to switch between to marked


locations.
Move cursor at marked label name
a.
Move cursor at marked label name
b.

Customizing vi: The .exrc file available in users home directory is use to change the behavior of
vi editor. Vi reads the startup file named as .exrc and vim reads .vimrc file at startup. The set, map
and abbr commands are used to change vi or vim behave, these commands can be used in vi ex
mode.

:help topic - If the topic name is unknown, then TAB completion will cycle through the
various options given the first few letters. Ctrl-d will print the complete list of possibilities.

:set all - Display all settings of vi


session.

:set ic - Change default to ignore case for text searches. Default is changed from
noignorecase to ignorecase. (ic is a short form otherwise type set ignorecase)

Following Common options used with set: The variables are in the form of
variable=value.

Full "set" Command Short form Description


autoindent/noautoindent ai/noai {CR} returns to starts next line at previous
indented level
autowrite/noautowrite aw/noaw Save file automatically when switch between file
using :n or :e
errorbells/noerrorbells eb/noeb Silence error beep sound
flash/noflash fl/nofl Screen flashes upon error (when noerrorbells is
set)
tabstop=5 ts Tab key displays 5 spaces
number/nonumber nu/nonu Display line numbers on screen
ignorecase/noignorecase ic/noic Ignore case when search a pattern
showmatch/noshowmatch Cursor shows matching ")" and "}"
showmode/noshowmode Editor mode is displayed at bottom of screen
taglength tl Default=0. Set significant characters
linelimit=2048560 Maximum file size to edit
wrapscan/nowrapscan ws/nows Breaks line if too long
wrapmargin=0/nowrapmargin wm/nowm Define right margin for line wrapping.
list/nolist Display all Tabs/Ends of lines.
bg=dark VIM: choose color scheme for "dark" or "light"
bg=light console background.
Mapping keys of keyboard (map) : The map command is use to assign a key with a sequence
of commands. It is useful to convert a sequence of keystrokes into a macro.

To map the key t with :w[Enter] which is use to save buffered text onto disk.

:map t :w^M ^M represents the [ENTER] key


:map #4 :!cc %^M Map function key F4 to compile the current c program. (% replaced
with current file name.
:map #5 :!./a.out^M Map function key F5 to execute the a.out file.
:map #6 :!%^M Map function key F6 to executes the current shell script or perl
program.

Note:- To map a sequence of commands with function keys then # (sign) and function key number
is used to map the appropriate function key. Vi automatically understands the current file as %
(sign).

Note:- The :map commands displays all mapped environment and :unmap cancels a command
mode map and :unmap! Cancels all an input mode map.

Abbreviating Text Input (abbr):- The abbreviate command is use to expand short string into
long words.
:ab ecb Engineering College Bikaner

When enter the word ecb and then press space bar it displays the long string as specified above.

Note:- Store all :set, :map, :ab commands in $HOME/.exrc (or .vimrc for vim) file so that they
are always available on vi or vim startup.

WILDCARDS :- There are two wildcards, namely ? and *. Unix shell provides some more

wildcards. [abc] Match one character which should be either a,b or c


[!abc] Match one character which is not a,b or c.
[p-t] Match one character which falls within the range p-t
[!p-t] Match one character which does not fall within the range p-t.

eg. $ls -id uni?[134] or $ ls my[!0-9]


eg. $mv uni[x-z][Twelve] /north

To Change File Writes:


$chmod 600 filename

4 = read, 2 = Write = 4+2 = 6 for user and remaining two bytes 00 for group and others
(the Groups and others have no writes)

$chmod 000 a1.txt :- There are no writes for user,group and others
$cat a1.txt :- Displays Message Permission Denied because user cant have writes to excess
this file.

Multiple Shell in Linux


1. bash Bourne shell : This is the Default shell
2. bsh bash shell
3. ksh korn shell
4. csh c shell

Note: CSH shell generally use for C programming and in unix the default shell is BSH

Ctrl + Alt + F1 Go into CUI (Character User Interface) or press Terminal button from
Task BarCtrl + Alt + F7 Go into GUI (Graphical User Interface)

$sh : Starts a new shell (Press Ctrl D or type exit to exit from new shell)

$vi demo.c : Create a c program


{
int i;
for(; ;); //infinite loop
}
$cc demo.c
$demo.out& : Sends output in background. (To send output in Background just place &
sing at end.)

$ps : Display process status to see the processes which are activated in background.
It displays PID (Process Identification No.), TTY, Time, CMD

$ps au : Display system activity. Linux is a multi-user operating system, Linux is also a multitasking
system. Multitasking means that many programs can be running at the same time. An
instance of a running program is referred to as a process. Ps au command displays all
running processes, monitoring system usage.

$kill -9 8308 : To terminate the background process. 8308 is PID No.


$ps a : Display all process even hidden also

Create two shells


$sh
$sh
$ps a

How to run multiple commands at the same time:


$date; who; ls l : Just type commands separated by semicolon.

$wc filename : Count the no. of Lines, words characters and spaces

$wc l filename : Counts the no. of lines

$wc c filename : Counts the no. of characters

$wc w filename : Counts the no. of words

$xterm : or
$startx : Go into GUI (Graphical User Interface) Mode

$shutdown r now : Turn off the computer


$init 0 : or
$ Ctrl Alt Del : To Reboot
$netconf : To Configure Networking

$ifconfig eth0 : To check the Ip Address

$fsck /dev/hda5 : Check & rectify the disk integrity

$e2fsck /dev/hda5 : Check & rectify the disk integrity

Note: The fsck and e2fsck both commands are same but e2fsck is more powerful.

$init 0/1/6 : 0 = Halt the system


1 = Boot system into single user mode
6 = Reboot the System
$passwd : To change the Password

$linuxconf : To configure everything in Linux (i.e networking, users, file system etc.)

$mount /dev/floppy : Mounts the Floppy disk, so that we can access floppy drive

$mount t vfat /dev/hda1 /mnt/win_c : To access windows partition in Linux.

$fstab : Display Mount points

Note : In fstab file specify all the devices which are mounted in linux at startup.

$banner <text> : Display a poster

How to Spell Check in Linux:


$ispell <filename> : Checks the spelling of specified file and display suggestion of
misspelled words.

$grep string filename : Find the specified string from file


$grep computer a1.txt : Find computer word from a1.txt file
$head -2 emp.txt : Display first two lines from top to bottom (-2 is number of lines to be
displayed)

$tail -2 emp.txt : Display last two lines from bottom to top.

$cut -c1-10 emp.txt : Display first 10 characters starts from column no. 1 to 10.
-c1 = Starts from column number
10 = End of column number
nd
$cut -f2 emp.txt : Display only 2 column
st
$cut -f1 emp.txt : Display only 1 column
$cut -f1,3 d | emp.txt : Display first and third fields (-d = deliminator)

$gzip abc.txt : Compress file (It is same as MS-Windows winzip command)


$gunzip abc.txt.gz : Uncompress file (unzip file)

How to go to from one user prompt to another user prompt. (we can change only six user prompts)

ALT + F1 : Change first user


ALT + F2 : Change second user
.
.
ALT + F6 : Change sixth user

$echo Linux Operating System : It Remove Spaces


Linux Operating System

$echo Linux Operating System : Cant Remove Spaces


Linux Operating System

$od filename : Display ASCII Octal value


$od -b filename : Display octal value of each character
$od -bc filename : Display octal value of each character along with corresponding character.

$split filename : Breakup a long file into small files


$split -60 a1.txt : Breakup file and each file contains 60 lines
$split a1.txt small : Breakup file and create files called smallaa, smallab, smallac etc.

grep :- grep is use to search a pattern from file and then display on standard output

device. Usages: $grep options pattern filename(s)

$grep marketing sales.txt :- It searches the pattern marketing and then display all those lines
they contains the pattern.

Note:- The pattern can also specified without quotes. The quotes only required when pattern
contains multiple words.

$grep Jitendra Singh

emp.txt grep options:-

-i : Ignore case for pattern matching.


-v : Inverse, Select all those lines they do not contains pattern.
-n : Display Line numbers they contains pattern.
-c : Counting total number of lines they contains pattern.
-l : Displaying file names they contains the matched pattern.
-e : Matches multiple pattern.
-f : Taking pattern from a file. The pattern may be specified one per line.
$grep c manager emp.txt
5
$grep c manager emp*.txt
emp1.txt:4
emp3.txt:6
emp7.txt:3
$grep l manager *.txt
emp.txt
emp1.txt
emp5.txt
$grep e manager e salesman e director emp.txt
$grep f patternfilename emp.txt
$grep n manager emp.txt
$grep v manager emp.txt
$grep [aA]g[ar][ar]wal emp.txt :- Regular expression is used to specify a group of
character enclosed within a pair of rectangular brackets[].

Asterisk * :- The wild card * is used to searches a pattern with grep. i.e. s* searches s ss sss ssss
. The * marks the previous character occurred zero or more times.

$grep [Aa]g*[ar][ar]wal emp.txt

The . Dot :- The . matches a single character like shell ?. i.e. 5. it matches five pattern
beginning with a 5 which is equilent to shells 5????.

The . along with * (.*) are also used continuously. They signifies any number of characters or none.

$grep raj.*choudhary emp.txt It searches raj choudhary or raj kumarchoudhary etc.

Specifying pattern location (^ and $) :- The ^ (care) match at the beginning of a line and $
matching at the end of a line.

$grep ^5 emp.txt
5001|Jitendra Singh|Computer Science|M.Tech.|8000
5002|Raj Kumar Choudhary|Information Technology|B.Tech.|8000
5003|Narendra Kumar|Computer Science|M.Sc.|6000
5010|Ajay Choudhary|Information Technology|B.E.|8000

To select all those records where salary lies between 8000 to 89999.

$grep 8$ emp.txt
5001|Jitendra Singh|Computer Science|M.Tech.|8000
5002|Raj Kumar Choudhary|Information Technology|B.Tech.|8000
5010|Ajay Choudhary|Information Technology|B.E.|8000

Note:- grep is also a filter so that it can search its standard input for the pattern and store the output
in a file.

$who | grep jitendra > users.txt It searches the user jitendra is logged in or not, if logged in then
stores the username into file users.txt.

Sed:- STREAM EDITOR:- It is a multipurpose tool which works of several filters. Sed
usages instructions which works on text. The usages of sed is as follows:-
sed options address action files(s)

Note:- The address and action are enclosed within single quotes. The address can be specified in
two ways:-
1. specify one or two lines like 3,4
2. Specify a / (forward slash) pattern) which occurs in a line (e.g. /pattern:/)
The first pattern specifies that to select a line or a set of multiple lines i.e. (2,6) to select a group of
contiguous lines and the second form uses one or two patterns. The action part can be use to
display (print) or can be used as a function like insertion, deletion or substitution of text.

Usages of sed:-

$ sed 5q std.txt

Note:- With sed we can use p(print) command to display lines q(quit) to print lines on screen
and then quit from file. It is same as Head command i.e. head n 5.

$sed n 6,11p std.txt :- Prints Lines from line no 6 to 11.

Note:- With p command use n switch otherwise p command prints the selected lines as well as all
the lines so that the selected lines prints twice. The $ symbol is used with sed to select the last line
from file.

$sed n $p std.txt :- Prints the last line from std.txt file.

Selecting multiple groups of line :- To select multiple lines then specify line numbers separated by
a space within a single quote.

$sed n 3,6p 11,15p $p std.txt :- It prints from line no. 3 to 6, 11 to 15 and the last line from file.

Negating the action (!) :- sed has a negation operator (!), which can be used with any action.

$sed n 10,$!p std.txt :- It prints from line no. 1 to 10. It is same as sed n 1,10p std.txt.

Multiple instructions with sed :- The e option used to specify multiple instructions and the -f
option is used to get the instructions from file.

$sed n e 2,4p e 9,11p e 16,19p e $p std.txt

$cat > inst1.txt


2,4p
9,11p
16,19p
$p

$sed n f inst1.txt std.txt :- It takes instructions from input file named as inst1.txt and then
prints from file std.txt.

Note :- We can also specify multiple input instruction files with f option and we can also combine
the
e and f options.
$sed n f inst1.txt f inst2.txt std.txt

$sed d e /director/p f inst1.txt f inst2.txt std.txt

Context Addressing :- The pattern must be bounded by a / on either side and we can also specify ,
(comma) separated pair of context addressing to select the group of lines.

$sed n /choudhary/p std.txt

$sed n /choudhary/,/chaudhary/p std.txt

$sed n 5,/choudhary/p std.txt :- Combine Line and context addresses.

Regular Expressions :- sed also usages to use regular expressions.

$sed n /[aA]gg*[ar][ar]wal/p std.txt :- It prints all the agarwals.

$sed n /sa[kx]s*ena/p /gupta/p std.txt :- Prints either saxenas or gupta.

Note:- sed also usages anchoring characters ^ and $, as part of of the regular expression.

$sed n /70.$/p std.txt :- It prints all the peoples born in the year 1970.

Storing selected lines into a file (w) :- The w (write) command writes the selected lines into
a separated file.

$sed n /director/w director.txt std.txt It save the lines of directors in director.txt file.

$sed n /director/w director.txt /manager/w manager.txt /supervisor/w supervisor.txt std.txt :-


It saves the selected lines into the separated specified files.

$sed n 1,50w fist 51,100w second 101,$w third std.txt :- It saves first 50 lines in first and next
50 lines into second and rest of the lines into third file.

Note:- With w command the n switch is used otherwise it stores selected lines as well as all
the lines.
Text Editing :- sed can insert text and change existing text in a file. We use i(Insert), a (Append), c
(Change) and d (Delete).

Inserting Text :-

$sed 1i\
> #include <netinet/in.h>\
> #include <sys/socket.h>
> server.c > $$

Note:- The 1i first inserts a line number at 1. The \ Indicates sed to this is not a last line.
$ mv $$ my.c ; head -2 my.c It first moves $$ file into my.c and then displays first 2 lines
from my.c

#include
<netinet/in.h>
#include <sys/socket.h>

Inserting a blnak line within each


line.

$sed \

my.c It inserts a blank line within each line in my.c

file. Deleting Lines (d) :-

$sed /manager/d std.txt :- It delete all those lines they contains the word manager from
file.

Finding & Replacing text :-

$sed s/cat/dog/ pets :- The pets file will be sent to standard output with the string cat
being replaced with string dog.

Note:- By default sed makes a maximum one change per line so that to make multiple changes per
line then use g (Global) command.

$sed s/cat/dog/g pets

$sed s/[Cc]cat/dog/g pets :- It searches with regular express and then perform replacement.
It searches both Cat and cat keywords.

Note:- By default sed works on strings not by words, To works on words then use
anchors.

$sed s/\<[Cc]at\>/dog/g pets

Note:- By default sed works on all lines in the file. It is also possible to works on selected
lines.

$sed 5,25s/cat/dog/ pets :- In this case the cat replaced with dog keyword only from line number 5
to
25 and rest of lines are unchanged.

$sed e s/cat/dog/g e s/cow/bull/g pets :- It searches multiple word with multiple


replacements.

Running Process in background :- In the multitasking system can do more than one job at a time.
Since on job can be running run in foreground and rest of the jobs can be running in background.
The
& operator and nohup commands are used to done this
jobs.
$sort o std.txt emp.txt & :- The shell immediately returns the PID and then returns to shell prompt
to accept any other command.

Running jobs after Log Out (nohup) :- When a user logged out, (in C shell and Bash Shell) the
shell is killed. The nohup (no hangup) command is used to run the process the continuously even if
the user is logged out.
$nohup ./server.out & :- The shell immediately returns the PID and displays a message
Sending output to nohup.out.

Note:- If we run more than one command in a pipeline, then use nohup command at the beginning
of each command.

$nohup ./server.out & | nohup grep Lecturer emp.txt &

Job Execution with Low Priority (nice) :- All the jobs in Unix normally executed with equal
priority. Which is not desirable because high-priority jobs must be completed at the earliest. The
nice command used with & operator to reduce the priority of jobs.

$nice ./server.out &

The nice values are system-dependent and typically range from 1 to 19. By default nice values
usages middle level value, usually 10. A higher nice value has a lower priority. The nice values
specified with the n switch.

$nice n 4 ./server.out &

Note:- A nonprivileged user can not increase the priority of a process, only superuser can change. The
nice value is displayed with the ps o nice command.

Controlling Jobs:- A job is the name given to a group of processes. If a job is running and we
expect to complete that job within 5 minutes and it goes on for half an hour. If we kill the job now
we will lose lot of work. If we using the C shell, Bash or Korn Shell then we can use job control
facilities to manipulate jobs.
Sends the current foreground job into background (bg)
Bring the last background job into foreground (fg)
List all the active jobs (jobs)
Suspend a foreground job (Ctrl+z)
Kill a job (kill)
The fg and bg commands are also used with the job number, job name or a string as arguments,
prefixed by the % symbol.

$fg %1 Brings first job into foreground.


$fg %sort Brings the shortest job into foreground.
$bg %2 Sends the second job into background.
$bg %?staff Sends to background job containing string staff

We can terminate a job with the kill command using the same manner as above. i.e. kill %1 kills
the first background job.

Job Scheduling (at and batch) :- Unix provides the sophisticated facility to schedule a job to run
at the specified time period of day.

One Time Execution (at) :- at takes as an argument time on which the job is executed and
then displays the at> prompt.
$at 19:25
at>./server.out
[Ctrl+d] To exit from the at prompt then at shows the job number in the form of number of
seconds that have elapsed since the Epoch.

The job goes in the queue and executed at 7:25pm today.

Note:- at does not indicate the name of the job to be executed so that the user must has to
remember the at jobs. The standard output or standard error of the job will be mailed to the user or
a user can alternatively redirect the output of the command.

$at 19:25
at>./server.out > report.txt

The f option is used to take commands from a file. The m option is used to send job
completion report to the user.

The at also offers many keywords now, noon, today, midnight, tomorrow and it also accepts the +
symbol to act as an operator.
$at 18 24 hour format assumed
$at 6pm
$at 6:15pm
$at noon At 12:00 hours today
$at now + 1 year At the current time after one year
$at 5:15pm + 1 day At 5:15pm tomorrow
$at 16:05 December 25, 2009
$at 10am tomorrow

Note:- The month name and the day of the week when used then they must be either fully spelled
out abbreviated to first three letters.

Note:- The jobs list is displayed with the at l command and removed with at r command.

Awk :- Named after its developers Aho, Weinberger, and Kernighan


The awk utility is a pattern scanning and processing language. It searches one or more files to see
if they contain lines that match specified patterns and then perform associated actions, such as
writing the line to the standard output or incrementing a counter each time it finds a match.

Some of the features of awk are:

Its ability to view a text file as made up of records and fields in a textual database.
Its use of variables to manipulate the database.
Its use of arithmetic and string operators.
Its use of common programming constructs such as loops and conditionals.
Its ability to generate formatted reports.

The usages of awk is as follows:-

$awk options selection_criteria {action} files(s)


The selection_criteria and action part both included in a single quotes and these can be specified
in one line or can also specified into multiple lines. If selection_criteria is missing, then action
part applies for all the lines of the file and if action part is missing then the entire line is printed.

Note:- Both selection_criteria and action part both are optional but not both at the same

time. In the action section { print } is used to prints the entire line.

$awk /manager/ emp.txt : By default it prints the entire line


those matches the string.
$awk /manager/{ print } emp.txt : Prints the entire line those match the string.
$awk /manager/ { print $0 } emp.txt : $0 represents the entire line, so that all of
the above commands are same.
Regular Expressions: We can use sed style regular expressions.

$awk /sa[kx]s*ena/ emp.txt

The F option is used to specify the Field separator. By default the field separator is a white
space instead of a single space or tab.

$awk F| /sa[kx]s*ena/ { print } emp.txt

Split a line into fields :- awk usages the special parameter $0 which represents the entire line and
also identifies the fields $1,$2,$3 and so on. ($1 represents first field, $2 means second field and so
on).

$awk F| /computer/ { print $2,$4,$6 } emp.txt : The , (comma) is used as a field delimit.
This means each field is separated to each others by a space.

Note:- If we omit the , (comma) then the fields glued together.

Select Line Numbers: The awk has an in-built variable NR which represents the line numbers.

$awk F| NR == 5, NR ==10 { print NR, $3,$4,$6 } emp.txt : It prints from line number 5 to 10
which is same as sed command sed n 6,11p emp.txt

Note:- NR == 5 is not assignment operator but it is a condition which is tested.


Formatted Output (printf) :- The C function printf used with awk to prints the formatted output. The
%s format is used with string and %d is used with numeric data.

$awk F| /sa[kx]s*ena/ { printf %3d %-25s %-10s %d\n,NR,$2,$3,$6 } emp.txt

Note:- By default character values are right justified so that (minus) sign is used to print
left justified. The \n is used for newline

Redirecting Standard Output:- Every print and printf statement can be redirected with > and |
symbol and the filename or command must be enclosed within double quotes.

$awk F| /sa[kx]s*ena/ { printf %3d %-25s %-10s %d\n,NR,$2,$3,$6 | sort } emp.txt


The above statement sorts the output of printf
statement.

$awk F| /sa[kx]s*ena/ { printf %3d %-25s %-10s %d\n,NR,$2,$3,$6 > sortfile }

emp.txt The above statement redirect the output into a separate file named as sortfile.

Comparision/Decision making:-

$awk F| $3 == lecturer || $3 == professor { printf %-20s %-12s %d\n,$2,$3,$6 }


emp.txt

It displays all those records they contains the specified match on third field. The logical operators
|| ,
&& and != works same as used in C.

$3 != lecturer && $3 !=
professor

Note:- When a specified match field contains trailing spaces then awk wont founds perfect

match. Match (~) and Negate (!~) Operators also used with regular expressions:

$2 ~ /[Cc]ho[wu]dh?ury/ || $2 ~ /[Cc]ha[wu]dh?ry/ Matches on second field


$2 ~ /[Cc]ho[wu]dh?ury | [Cc]ha[wu]dh?ry/ It is also same as previous
$3 !~ /lecturer|professor/ Neither lecturer nor
professor

Note:- To match a string embedded in a field the use ~ instead of == and to negate a match then use !
~
instead of !=.

Note:- If we want to search a pattern which is embedded into the string. i.e. to search only g.m. but
it also embedded into d.g.m. awk usages ^ (match at beginning of field) and $ (match pattern at the
end of the field) characters to match at beginning and end of a field.

$awk F| $3 ~/^g.m./ { printf $2,$3,$6 } emp.txt It searches only g.m. and discarded
d.g.m.

Storing awk program into a file ( -f ) :- When the program is stored into a file then the
stored program is not enclosed within quotes. The single quotes only used when program is
written at command prompt.

$vi emp.awk
$3 == lecturer && $3 == professor {
printf %-20s %-12s %d\,$2,$3,$6 }

Number Processing :- With awk command we can use all the relational operators (<, <=, >, >=,
==,
!=, ~ match a regular expression, !~ dont match a regular expression) and arithmetic operators
(+,-,*,/
%) which are used in C
language.
$awk F| -f emp.awk emp.txt The f filename is used to specify program file
name.

$awk F| $6 > 8000 { printf %-20s %-12s %d\n, $2,$3,$6 }


emp.txt

awk handles both integer and floating type numbers. We can also combine regular expression
with numeric comparisons. Locate all those records they born in 1985 or they drawing basic pay
greater than 8000.
$awk F| $6 > 8000 || $5 ~/85$/ emp.txt

$awk F| $3 == lecturer { printf %-20s %-12s %d %d %d,$2,$3,$6,$6*0.4,$6*0.15 } emp.txt

The above command calculates the dearness allowance ( @40% of basic pay) and house rent (@15%
of basic pay).

Variables :- awk has certain built-in variables i.e. NR,$0 and it also permits the user to define
user- defined variables. The user defined variables has two special features.
No data type declarations required.
By default variables are initialized to zero or a null string depending on its type.

$awk F| $3 == lecturer & $6 > 8000 { ctr = ctr + 1, printf %3d %-20s %-12s
%d\n, ctr,$2,$3,$6 } emp.txt
$awk F| $3 == lecturer & $6 > 8000 {printf %3d %-20s %-12s %d\n, ++ctr,$2,$3,$6 }
emp.txt

The initial value of ctr is 0 (by default). We can also use C style i.e. ctr++, ctr += 2, ++ctr

The BEGIN and END Section:- The awk statements are applied for all the lines selected by the
address. But if we want to print something before and after the processing then the BEGIN and
END sections are used.

BEGIN { action } Both requires curly braces and both are optional
END { action }

$vi emp2.awk
BEGIN {
Printf \t\t\tEmployees Record\n\n
} $6 > 8000 {
ctr++ ; total += $6
printf %3d %-20s %-12s %d\nctr,$2,$3,$6
}
END {
Printf \n\t\tThe Average Basic Pay is = %6d\n,total/ctr
}

$awk F| f emp2.awk emp.txt

Note:- Always starts the opening brace in the same line with the section BEGIN or END
otherwise awk generate some strange messages.

Built-In Variables:- awk has several built-in variables and all are assigned automatically.
----------------------------------------------------------------------------------------
- Variable Function
----------------------------------------------------------------------------------------
- NR Cumulative number of lines read
FS Input Field Separator
OFS Output Field Separator
NF Number of Fields in the current line
FILENAME Current input file name
ARGC Number of arguments in command line
ARGV List of arguments
-----------------------------------------------------------------------------------------

The FS Variable:- The awk usages the space as the default field delimiter. FS redefines this field
separator and it must occur in the BEGIN section. This is an alternative to the F option used in
the command. BEGIN { FS=| }

The OFS Variable:- In the print statement comma-separated arguments usages the field separator is
a space. To change it then we use OFS and it also must occur in the BEGIN section. BEGIN {
OFS=|}

The NF Variable:- It contains the total number of fields in the line.

$awk BEGIN { FS = | } NF != 6 {
print Record No , NR, has , NF, Fields } emp.txt

The FILENAME variable:- It stores the current file name which is processed. Like grep, sed,
awk also handle multiple filenames in the command line. By default awk does not print the
filename
$6 < 5000 { print FILENAME, $0 } It prints the filename also.

Creating a variable:
<variable name>=<value>

$name=Jitendra
$echo $name : To evaluate the value of a variable, Just prefix a $ sign before variable
Jitendra name

Simple arithmetic on shell variables:


$expr 4+10 : expr can be used to evaluate arithmetical computations on the shell variables
14 having integer value.

$expr 8-2 # It prints 6


$expr 45/5 # It prints 8

$sum=expr 25+5
$echo $sum # IT prints 30
$x=12
$y=80
$echo sum is $x+$y
sum is 12 + 80
$echo sum is expr $x + $y # It prints sum is 92

$sum=expr $x+$y
$echo $sum
92
A simple shell program to read two numbers and print sum of two numbers

vi sum.sh

echo e \n Enter First Number : \c


read a
echo e \n Enter Second Number : \c
read b
let sum = $a + $b
echo e \n The Sum of two numbers = $sum
----------------------------------------------------------------
Note:- let command is used for calculation in shell script and we can use arithmetic operators
+ - * / and %.

$let sum=5+6 #There is no white space after variable name


$echo $sum # It prints 11

$let sum= 2 * 6 + 6 / 2
$echo $sum #It prints 15

$let x=3 y=5 z=4 OR $let x=3 y=5 z=4 # The $ sign not required by let
$let z=x+y+$z $let a=x+y+z
$echo $z $echo $z

The second form uses the ( ( ) ) operators that replace the let statement

itself e.g.
$let x=2 y=3 z =5
$((z =x+y +z)) # The white space is unimportant
$echo $z # It prints 10

$((z=z+1)) # We can also use ((z+=1))


$echo $z # The result is 11

Note:- let and its twin ( () ) also allow you to use then as control commands in any of the
shells programming constructs. This will certainly speed up script execution.

Note:- Bash shell cant support escape sequence characters i.e. \n \c \t etc, so that e option is
used for supporting an escape sequence characters.

Relational Operators:- Relational operators are start with a minus (-) sign.
-eq Equal to
-ne Not Equal to
-gt Greater Than
-ge Greater than Equal to
-lt Less Than
-le Less than Equal to
Assignment of variables:
$x=5; y=4; z=3

Conditons:-

if [ condition ] or if test condition


then then
<Statement> <Statement>
else else
<Statemdnt> <Statement>
fi fi

e.g.

if [ $a gt $b ]
then
echo e \n Value of a is greater than value of b
else
echo e \n Value of b is greater than value of a
fi

---or---

if test $a gt $b
then
echo e \n Value of a is greater than value of b
else
echo e \n Value of b is greater than value of a
fi

Note :- test can be used to compare strings and logical operators (= and !=) are used.

Note:- -z and n options are used to check for a null

string e.g.

vi stcheck.sh

echo e Find What: \c


read $word
if [ -z $word ] ; then
echo You could not entering a word which you want to find
exit 1
else
echo e Enter filename from which you to find : \c
read filename
if [ ! n $filename ] ; then
echo File name cant specified!!!
exit 2
else
grep $word $filename || echo Specified word cant found
fi
fi

Note: To check more then one condition, the test permits a (AND) o (OR)
operators e.g.
if [ -n $word -a n $filename ] ; then
grep $word $filename || echo Not Found..!!
else
echo At least one value of a variable was a null string
exit 1
fi
Note: -a option is used as AND operator and o option is used as OR operator.

e.g.
if [ $choice = y o $choice = Y ]

String Tests:-
-n string :- True if string is not a null string
-z string :- True if string is a null string
v1 = v2 :- True if string v1 = v2
v1 != v2 :- True if string v1 is not equal to v2
string :- True if string <string> is specified and not null

Case Conditional
Case <expression> in
Pattern1) <statement>
;; Pattern2)
<statement> ;;

esac

e.g.

echo MENU
echo 1. Display directory list
echo 2. Display current date
echo 3. Display free memory space
echo 4. Exit
read choice
case $choice in
1) ls l ;;
2) date ;;
3) df ;;
4) exit
esac
Testing Files :- The f option used with !
operator e.g.

if [ -f abc.txt ] ; then
echo File is an ordinary file
fi

vi test.sh

if [ ! e $1 ] ; then
echo File does not exist
elif [ ! r $1 ] ; then
echo File is not readable
elif [ ! w $1 ] ; then
echo File is not writable
else
echo File is both readable and writable
fi

$sh test.sh xyz.doc // to Execute the shell script, xyz.doc is replaced with $1

Options used for checking files:

-e filename : True if file exist


-f filename : True if file exist and is a regular file
-r filename : True if file exist and is a readable
-w filename : True if file exist and is a writable
-x filename : True if file exist and is a executable
-d filename : True if file exist and is a directory
-s filename : True if file exist and has a size greater than zero

sleep <no.of seconds> : Delay temporary pause

sleep 30 : Pauses for 30 seconds

Iterations / Loops

While [ Condition ]
do
<Statements>
<Statements>

done

Q. Write a shell script which will read item code and item name and store into a file called
itemmaster.

vi item.sh
morerec=y
while [ $morerec = y ]
do
echo e \nEnter Item Code and Item Name: \c
read itemcode itemname # It Reads both variables
echo $itemcode | $itemname >> itemmaster # Append a new line into itemmaster
file echo e Do you want to add more records (y/n)? \c
read morerec
case $morerec in
y*|Y*) morerec=y ;; # It accepts y, Y, yes, YES
n*|N*) morerec=n ;; # It accepts n, N, no, NO
*) morerec=y ;; # When pressing any other character means y
esac
done

$sh item.sh # To execute the shell script

Note: Instead of y* | Y*) and n* | N* , we can also write:

[yY][eE]*) ;; # It Matches YES, yes, Yes, yES, etc


[nN][oO]) ;; # It Matches No, no, nO, NO, etc.

Setting up an Infinite loop


While true # True command always returns a true value
do
date # After every 300 seconds displays date on
screen sleep 300
done & # & sign after execution done runs loop in background

Note: There is also a command false that always returns a false value. The break command is use
to terminate the loop.

Q Write a function that takes a path as a command-line argument, creates all the directories in
the path and changes the current directory to the last directory in the path.

Ans:- Usage createpath <Path>

echo $1 > anyfile


set `sed s/\// /g anyfile`
mkdir $*
a=$*
i=$#
while [ $i ge 1 ]
do
set $a
shift `expr $i - 2`
mv $2 $1
I=`expr $i - 1`
done

Q. Write a shell script which will receive the file name or its full path as the command line
arguments. The script will obtain information about this file from the ls l command and display
this information in a user-friendly manner.
Ans :- Usage: Display <file or path>, Stored in file display

ls l $1 $1 > anyfile
set `sed `sed s/-// anyfile`
echo File permission: $1
echo There are $2 links
echo Owner of the file is $3
echo Group owner is $4
echo It occupies $5 blocks
echo The file was created on $6 $7 at $8

Q Write a shell script that will accept a string from the user. The script will replace all blank
spaces with a -. There should be not more than one - , as the delimiter between the words.

Ans:-

Echo Enter a string


read str
if [ -z str ]
then
exit
else
else $str | sed s/ /-/g
fi

Q Write a command to display the publisher and author of the Computer Organization book
which was most recently purchased (use the file book.lst).

Ans:- We will require four commands in a pipeline to have the required output as

follows:- grep Organization book.lst | sort -t| +3.5 -r | cur -d| -f3,5 | head -1

Note: The grep command will select lines containing the pattern Organization
The sort command will sort the lines on the date-of-purchase field. t| specifies that the field
delimiter is pipe (|). +3 specifies to sort after skipping first three fields (i.e. sort the fourth field).
3.5 is used to indicate to start sorting after skipping first five characters in the fourth field (i.e. that
date field). r option reverses the sort (i.e. sorts in the decreasing order of date).
cut d| f3,5 will select the publisher name and author name fields from the selected
lines. Head -1 will display the topmost line in the list, i.e. the most recently published
book.

Q. Write a sed command to insert two spaces at the end of each line of a file text.txt
Ans :- sed s/$/ / text.txt.

Shell Functions :- Like in other programming languages, you can create and use functions in
shell scripts.

e.g.
#file func_sh
user() # defining function
{
echo Currently logged users are
who
}
echo Do you want to see user-list
read ch
if [ $ch = y ]
then
user # function is called
fi

Q. Write a Shell script to print a file in reverse order.

# reverse.sh
# Printing file in reverse order
# Count total no. of lines and then extract line from file and store into
newfile n=cat $1 | wc l
m=1
while test $n gt 0
do
tail -$m $1 > newfile
h1=head -1 newfile
echo $h1
let n=$n-1
let m=$m+1
done

Note: It is also possible to print a file in reverse order using awk.

#reverse.sh
#usages: sh reverse.sh myfile.txt
if test $# -ne 1
then
echo Usages: `basename $0` FileName_to print in reverse order
exit 1
else
awk { line[NR] = $0 } END { for (i = NR; i > 0; i--) print line[i] } $1
fi
----------------------------------------------------------------------------------------------------------------
Q. Write a Shell script to modify cal command to accept more than one month
# cal1.sh
# Accept month numbers as command line
arguments if test $# -ge 1
then
let n=0
let month=$#
while test $month -ne $n
do
let n=$n+1
cal $1 2009
shift
done

else
echo "Usages: `basename $0` Month no.s as command line argument"
fi

[jitendra@ntserver shellscripts]$ sh cal.sh 004 06 09


April 2010
Su Mo Tu We Th Fr Sa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30

June 2010
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

September 2010
Su Mo Tu We Th Fr Sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30

[jitendra@ntserver shellscripts]$

Q. A shell script to perform real numbers. (Store real numbers and then put real number variables
into bc to perform real numbers operation).

a=5.65
b=3.45
c=`echo $a + $b | bc`
echo $a + $b = $c
Q. A shell script to count total no. of lines, words and characters without using wc command.

#script.sh
#Usages: Filename as an argument
if test $# -ne 1
then
echo Usages: `basename $0` FileName to count Lines,Words and Characters
exit 1
else
awk 'BEGIN {
print "Counting Lines Words and Characters"} { char+=length ; words+=NF ; lines=NR
}
END {
printf "%12d %6d %11d \n",lines,words,char
}' $1
Fi

[jitendra@ntserver shellscripts]$ sh prg9.sh my.txt


Counting Lines Words and Characters
6 16 280
[jitendra@ntserver shellscripts]
$

Q. Write a shell script to printing stars.

#stars.sh
echo Printing Stars
for (( i=1; 1<5; i++))
do
for (( j=1; j<=I; j++))
do
echo -n *
done
echo
done
for ((i=4; i>=1; i--))
do
for ((j=1; j<=i; j++))
do
echo n *
done
echo
done

[jitendra@ntserver shell]$ sh stars.sh


Printing Stars.........
*
**
***
****
*****
****
***
**
*
[jitendra@ntserver shell]$

Q A Shell script to print stars (for loop different uses)

#forloop.sh
MAX=0
echo n Enter Numbers between ( 3 and 9) :
read MAX
if ! [ $MAX -ge 3 a $MAX le 9 ] ; then
echo I ask to enter numbers between 3 and 9
exit 1
fi
clear
for (( i=1; i<=MAX; i++))
do
for (( j=MAX; j>=i; j-- ))
do
echo n
done
for (( k=1; k<=i; k++ ) )
do
echo n *
done
echo
done
## Second Stage ##
for (( i=MAX-1; i>=1; i-- ))
do
for (( j=i; j<= MAX; j++ ))
do
echo n
done
for (( k=1; k<=i; k++))
do
echo n *
done
echo
done

[jitendra@ntserver shell]$ sh forloop.sh


Enter Numbers between (3 and 9) : 6
*
**
***
****
*****
******
*****
****
***
**
*
[jitendra@ntserver shell]$

What is a system Call :- A system call is a call to the operating system that requests the kernel
to carry out certain low-level operations. Programmers can use the system calls read() and write() to
perform I/O operations.

NIS :- Network Information Service was created by Sun Microsystems as a way of managing
information that is shared among a group of host computers on a network. By using NIS
Computers can share a common set of user accounts, user groups and TCP/IP host names, as well
as other information.

Note :- NIS was originally called Yellow Pages, but sun had to change this name because it
was trademarked.

The group of computers that the master NIS server supports is referred to as an NIS domain.

Setting up Redhat Linux as an NIS Client :- We needs following information to setup NIS

clients a) NIS Domain Name :- Group of hosts that use the common set of NIS files.
b) NIS Master Server Name :- Name of the computer on the network that maintains the NIS
Databases and responds to requests from the network for that information.

1. Define NIS Domain Name :- The domainname command is used to setup NIS domainname.
i.e. domainname ecb.ac.in

Note :- To verify that NIS domain name is set, just type domainname then it returns NIS
domain name. As soon as when you reboot the computer, it is gone.

To make the domain name permanent then we need the domainname command run
automatically each time when system boots. Then edit the /etc/init.d/network file and add the
following line:-
domainname ecb.ac.in

Note:- If the domain name is wrong then ypbind daemon is failure.

2. Setting up the /etc/yp.conf file :- ypbind daemon needs information about NIS domain
and NIS servers for it to work. IF NIS domain name is ecb.ac.in & the master server name
is ecbserver then the following entry will be in /etc/yp.conf file:
domain ecb.ac.in server ecbserver
3. Configure NIS Client daemon :- After NIS client information is set up, we need to run NIS
as a client is start the ypbind and ypwhich daemons.

The master ypbind process handles requests for information from the NIS server. The ypwhich
daemon finds the NIS master server.

4. To setup an existing run-level script called ypbind to start automatically at boot time.

Type following command as root #chkconfig ypbind on

Or we can also type the following commands to link the ypbind run level script so it starts at
boot.

#ln s /etc/init.d/ypbind /etc/rc3.d/S13ypbind


#ln s /etc/init.d/ypbind /etc/rc5.d/S13ypbind

5. Enter the following command to immediately starts the ypbind service.

#service ypbind start


or
#/etc/init.d/ypbind start

Note : Instead of start we can also use stop (to stops the service), restart (to restart the service), status
(To find out the current status of a service i.e. service is running or stoped)

6. Checking that NIS is working or not :

#ypwhich It returns the NIS Server Name.


#ypcat hosts Check the maps are being shared.

7. NIS Maps :- To generate the NIS maps then configure the /etc/nsswitch.conf file to
include in the search path.

passwd: files nis


shadow: files nis
group: files nis
hosts: files nis

Note: For each of these entries, the original files are checked first (/etc/passwd, /etc/shadow and
so on), then the nis server is checked.

Note:- As soon as the /etc/nsswitch.conf file is changed, the data from the NIS maps are
accessible, there is no need to restart the NIS service.
Note: We can also use authconf to configure NIS

Setting up NIS Master Server :- To configure linux system as NIS master server, you
should first configure it as NIS client. Then create the NIS maps and configure the NIS master
server
daemon process (ypserv and rpc.yppasswdd).
1. Create NIS maps :- In /var/yp directory a Makefile enables you to configure which files
are being shared with NIS.

a) Choose files to map :- Specify all the files which you want to maps in the all entry: e.g.
all: passwd group hosts rpc services netid protocols mail \
# netgrp shadow publickey \

Note :- To build NIS maps, your system must have awk, make & umask commands. The locations of
these commands are /usr/bin/gawk, /usr/bin/gmake and umask ( The umask command is a shell
built in command, so that we dont have to look for its location).

2. Define NIS client access :- By default any computer on any network that can reach NIS
master, can access maps.
3. Generate NIS Maps :- Enter the following command to generate maps :
#/usr/lib/yp/ypinit m

Add a server name at a time and then press ^d then verify that the list of servers is correct (press
y). The database is built at this point. A new directory named NIS domain name is created in
/var/yp directory.

4. Configure NIS server daemons :- Enter following commands to configure NIS


server daemons:
#chkconfig ypserv on
#chkconfig yppasswdd on
#service ypserv start or #/etc/init.d/ypserv start
#service yppasswdd start or #/etc/init.d/yppasswdd start

Setting up NFS Server :- There are 3 main configuration files you will need to edit to setup NFS
server. /etc/exports, /etc/hosts.allow, /etc/hosts.deny. You only need to edit the /etc/exports to
get NFS works.

In the /etc/exports file put an entry in the following format :

Directory machine1(option11,option12) machine2(option21,option22)

Directory :- The directory that you want to share. It may be an entire volume though it need not

be.

Machine1 & Machine2 :- Client machines that will have access to the directory. The machines
may be listed by their DNS address or their IP address (e.g. Lab5-1.ecb.ac.in or 192.168.5.6). Using
IP address is more reliable and more secure. If you need to use DNS addresses, and they do not
seem to be resolving to the right machine.

Optionxx :-

ro :- The directory is shared read only. The client machine will not be able to write to it. This
is the default.

rw :- The client machine will have read & write access to the directory.
no_root_squash :- By default, any file request made by user root on the client machine is
treated as if it is made by user nobody on the server, if no_root_squash is selected, then root on
the client machine will have the same level of access to the files on the system as root on the
server.

no_subtree_check:- If only part of a volume is exported, a routine called subtree checking


verifies that a file that is requested from the client is in the appropriate part of the volume. If the
entire volume is exported, disable this check will speed up transfers.

sync:- By default all version of exportfs command will use async

behavior. i.e. /etc/exports

/usr/local 192.168.0.1(ro) 192.168.0.2(ro)


/home 192.168.0.1(rw) 192.168.0.2(rw)
Note :- Here we share /usr/local read-only to slave1 and slave2, because it probably contains our
software & there may be benefits to allowing slave1 & slave2 to write to it that outweigh
security concern. The /home directory need to be exported read write if users are to save work
on them.

/home 192.168.0.0/255.255.255.0(rw) :- All the client network computer they


are present on network 192.168.x.x can access the servers home directory.

To force nfsd to re read the /etc/exports file, give the following command :-
#exportfs a v
Setting up NFS Clients :- Modify the /etc/fstab file to mount the servers shared directory when
the system is booting :-

Enter the following entry in /etc/fstab file.

Servername:/home /home nfs defaults 0 0

Deleting User Accounts :- The userdel command is use to delete an user account.

#userdel username :- It deletes the user account but cant delete users home directory.

#userdel -r username :- Delete user account as well as his home directory also.

Searching :- To find out a user which is already exist or not.

#find / -user username print :- Search all the files starting from / (root directory) for all files &
directories owned by specified user and print the filename on screen.

#find /home -user username exec rm {} \; :- Search all files and subdirectories under the
/home that are owned by username. Then run the rm command to delete each of those files.

#find / -user oldusername -exec chown newusername {} \; :- Search all files and directories
under / root that are owned by user oldusername and run the chown command to change each file,
so that it is owned by newuser instead.
#find / -uid uid-no chown newusername {} \; :- Same as previous command but it usages the
user id number instead of olduser name, to identify the matching files. This is useful when we
deleted a user before converting her files.

-print :- Lists the matching files.


{} :- The {} characters designate where the matching filename should be filled in when find runs
the exec option.

\; :- Tells linux where the command ends.

Installing Applications :- 1. To install RPM Files :- The rpm command has these modes
of operations:-

-i = Install -U = Upgrade package -q = Query


-v = Verify -e = Uninstall --setperms = Fix
-b = Build --checking = Signature CheckPermissions
--rebuilddb = Rebuild database.

e.g.

#rpm -i [options] package:- To install RPM archive files.

Note:- Along with i option, we can use these options to bet feedback.
-vv Prints the debugging information during installation.
-h Prints 50 hash marks (#) as the package is unpacked.
-percent Prints the percentage of the total package that has been installed.

Note :- rpm checks before installing a package to make sure that it is not overwriting newer files
or installing a package that has dependencies on other packages that are not installed.

i.e. # rpm -ivv packagename.rpm

Note:- The following options can be used to override conditions that may otherwise cause
the installation to fail.

--force :- Forces the contents of the current package to be installed, even if the current
package is older than the one already installed (it is same as oldpackage, replacefiles, replacepkgs
options)

--oldpackage :- The package to be installed, even if the current package is older than the one
already installed.

--replacefiles :- The package to be installed, even if the files were placed there by other package.

--nodeps :- Skip package dependency checks and installs the package, even if packages
it depends on or not installed.

--ignorearch :- The package to be installed, even if the binaries in the package dont match
it depends on or not installed.
--ignoreos :- The package to be installed, even if the binaries in the package dont match
the architecture of you operating system.

i.e. #rpm -U --oldpackage package-name.rpm

Removing Packages :-

#rpm -e package-name :- Remove the package if there are no dependencies on


this package, it is silently removed.

#rpm -evv package-name | more :- This shows the files that are being removed one page
at a time.

#rpm -evv --test package-name :- This test mode shows you everything that
would
happen in the uninstall without actually uninstalling. You can always run the uninstall in test move (
-- test ) before you do the real uninstall.

Querying Package :-
#rpm -qa package-name :- Lists all installed package.
-qi :- Lists lots of information about a package (i.e. Version no.,
Company, Date, Size etc.)
-ql :- Lists all the files contained in the package
-qc :- Lists all configuration files that comes in the package
-qd :- Lists all documentation files that comes in the package.

Using mkbootdisk in RedHat and derivatives to create a new bootdisk:


1. Look in /lib/modules and select the appropriate kernel version.
2. Place a floppy in the drive.
3. #mkbootdisk --device /dev/fd0 2.x.y-z (the latter number should be your kernel
version)
4. Remove you new boot floppy and test it.
**************************************************************************
DNS :- A static IP address is necessary to assign the server a host name in domain name system. You
wants one static ip address for each computer that you make publicly accessible to the internet.

Checking domain name availability :- In Linux the whois command is use to checks the
domain name availability.

i.e. #whois ecb.ac.in

Add DNS Server Information :- The other computers on your LAN point to your DNS servers
to resolve domain names to IP addresses (The /etc/resolv.conf file is where you identify your
DNS servers).

DNS Server Usages the Port No. 53. To see which ports are assigned to which services by
default see the /etc/services file.
The Domain Name System DNS is essentially a distributed database that translates host names into
IP
addresses. (and IP addresses back to hosts names.)

DNS Configuration Files :- (/etc/named.conf & /var/named/*)

1. vi /etc/named.conf :- To Add the DNS Zone entry.

i.e. zone ecb.ac.in IN {


type master;
file ecb.ac.in.zone;
};

2. vi /var/named/ecb.ac.in.zone

$TTL 86400
;name class type fully qualified Administrator Email
; domain name address

@ IN SOA ns1.ecb.ac.in. root.ns1.ecb.ac.in. (


1 ; Serial
28800 ; Refresh
14400 ; Retry
36000 ; Expire
86400 ) ; Minimum
; Name Servers
IN NS ns1.ecb.ac.in.
IN NS ns2.ecb.ac.in.
; Mail Servers for Domain
IN MX 10 mail.ecb.ac.in.
IN MX 20 cse.ecb.ac.in.
; Public Servers

ns1 IN A 123.45.61.1
ns2 IN A 123.45.61.2
mail IN A 123.45.61.3
www IN A 123.45.61.2
**************************************************************************
$TTL 3D :- Zone Time to Live (TTL) value, TTL is to reduce the number of DNS queries
the authoritative DNS server has to answer.

Name :- The root name of the zone. The @ sign is a shorthand reference to the current origin (zone)

Class:- There are no. of different DNS classes IN or Internet Classes.

Type :- The type DNS resources record. i.e. SOA is resource record, NS, MX, A, CNAME, PTR

Name Servers:- Fully qualified name of your primary name server.


Serial :- Increase the Serial No. to alert other servers that they need to get fresh data about
your domain.

Refresh :- Define how often the slave DNS for the zone checks for changes.

Retry :- If the slave cant reach the master retry again after 14400 seconds.

Expire :- If slave cant contact the master within the expire time, the slave discards the data.

Minimum:- Defines the cache time to live for negative answer.

The (NS) define the name servers that represent this zone. NS record define hosts with the names ns1
& ns2 in ecb.ac.in.

The (MX) record indicates the location of the mail server for the domain, so that the DNS server
can direct email to users in ecb.ac.in.

To Check the zone file is correctly formed.

i.e. #named-checkzone ecb.ac.in /var/named/ecb.ac.in.zone

To starting the named (DNS)

daemon. i.e. #/etc/init.d/named

start

To Checking that DNS is working.

#dig ecb.ac.in or #nslookup www.ecb.ac.in


#host www.ecb.ac.in or #host 123.45.61.2
Bind :- Bind is an acronym for the Berkeley Internet Name Domain project, which is a group that
maintains the DNS related software suite that runs under linux.

Samba :- Samba is a software package which is use to share file system and printers on a network
with computers that use the Session Message Block (SMB) protocol. Samba configuration file
present in /etc/samba/smb.conf.

Daemon processes consist of smbd ( the SMB daemon ) & nmbd (the NetBIOS name server).

We can check the configuration file using testparm & testprns commands. The smbstatus
command will tell you which computers are currently connected to your shared resources.

Using the nmblookup command, we can query for NetBIOS name (The names used to identify
host computers in samba).

Samba usages the NetBIOS service to share resources with SMB

client. [global]
name resolve order = wins bcat hosts
workgroup = ECB
netbios name = CCLAB
Server String = Samba server on %v
hosts allow = 192.168.0. 192.168.1.
share modes = yes
passwd program - /usr/bin/passwd %u
max disk size = 10000
dns proxy = no
logon script = %U.bat
local master = yes
os level = 33
security = user
Printcap name = /etc/printcap
Load Printers = yes
Printing = cups
Log file = /var/log/samba/%m.log #%m automatically replaced with each host name.
Max log size = 0
Encrypt passwords = yes
Smbpasswd file = /etc/samba/smbpasswd
Dns proxy = no
add machine script = /usr/sbin/useradd -s /bin/false -d /tmp %u
add user script = /usr/sbin/useradd -m %u
delete user script = /usr/sbin/userdel -r %u
add group acript = /usr/sbin/groupadd %g
delete group script = /usr/sbin/groupdel %g
add user to group script = /usr/sbin/usermod -G %g %u
logon drive = Z:
username map = /etc/samba/smbusers
domain master = yes
encrypt passwords = yes
logon home = \\%L\%U
wins proxy = yes
wins support = yes
server string = ECB Server
path = /var/spool/samba
unix password sync = yes
logon path = \\%L\Profiles\%U
preferred master = yes
pam password change = yes
domain logon = yes
max log size = 50
log file = /var/log/samba/%m.log
printer = hp9000
map acl inherit = yes
[home]
Comment = Home Directories
Browsable = no
Create mode = 0664
Directory mode = 0775
Max connections = 4
Writable = yes
[printers]
Comment = All Printers
Path = /var/spool/samba
Browsable = no
Guest ok = no
Printable = yes

[netlogon]
comment = Network Logon Services
path = /home/share/netlogon
guest ok = no
writable = no
browseable = no
share modes = no
root preexec = /home/share/scripts/makelogonscript.1 %U %L %G
root postexec = rm /home/share/netlogon/%u.bat

[Profiles]
path = /home/share/profiles
browseable = no
guest ok = yes
writeable = yes
root preexec = /bin/mkdir /home/share/profiles/%U; \
/bin/chown %U /home/share/profiles/%U; \
/bin/chmod 700 /home/share/profiles/%U

[Learning]
comment = File Provided by Teachers to Students
path = /home/share/learning
writeable = no
browseable = yes
read only = yes
public = yes
force create mode = 664
force directory mode = 775

[Printers]
comment = HP 9000 Printer in Computer Lab
path = /var/spool/samba
browseable = yes
guest ok = no
printable = yes
use client drivers = yes

Installing Boot Image When boot loader is crupted


1. Boot from Linux CD 1
2. Choose Linux Rescue : Select Newtworking Y/N to NO
3. #chroot /mnt/sysimage
4. #grub-install /dev/hda
5. #reboot

To configure ADSL Package : Install rp-pppoe Package and the configure


following parameters:-
1. userid 2. Network Interface (eth0 or .)
3. Demand Value (Normally you can leave it blank.
4. DNS Information (Primary & Secondary)

Note: Normally DNS information leave it blank (automatically accepted)

#adsl-setup

Enter UserName?
i. Enter you PPP0E UserName?
ii. Enter the Ethernet Interface connected to the ADSL Modem? Eth0
iii. DNS .? 61.1.128.5 61.0.0.5
iv. Password.?
v. Firewall? 0 = None, 1 = Standalone 2 = Masquerade (Choose 2 a type of Firewall)
vi. Accept these settings (y/n)? Y
Adjusting.. /etc/ppp/ppp0e.conf & /etc/resolv.conf

#adsl-start : To start the connection


#adsl-status : Check status of connection
#adsl-stop : To stop the connection.

#lsmod : Listing Loaded Modules. i.e


Com1 : /dev/tty/S0
Com2 : /dev/tty/S1

Difference between Linux and Unix


LINUX UNIX
What is it? Linux is an example of Open Unix is an operating system
Source software development that is very popular in
and Free Operating System universities, companies, big
(OS). enterprises etc.

Cost Linux can be freely distributed Different flavors of Unix have


downloaded freely, distributed different cost structures
through magazines, Books etc. according to vendors
There are priced versions for
Linux also, but they are
normally cheaper than
Windows.
User Everyone. From home users to Unix operating systems were
developers and computer developed mainly for
enthusiasts alike. mainframes, servers and
workstations except OSX,
Which is designed for
everyone. The Unix
environment and the client-
server program model were
essential elements in the
development of the Internet

Manufacturer Linux kernel is developed by Three biggest distributions are


the community. Linus Solaris (Oracle), AIX (IBM) &
Torvalds oversees things. HP-UX Hewlett Packard. And
Apple Makes OSX, an unix
based os..

Usage Linux can be installed on a The UNIX operating system is


wide variety of computer used in internet servers,
hardware, ranging from workstations & PCs.
mobile phones, tablet Backbone of the majority of
computers and video game finance infrastructure and
consoles, to mainframes and many 24x365 high availability
supercomputers. solutions.

Development and Linux is developed by Open Unix systems are divided into
Distribution Source development i.e. various other flavors, mostly
through sharing and developed by AT&T as well as
collaboration of code and various commercial vendors
features through forums etc and non-profit organizations.
and it is distributed by various
vendors.

GUI Linux typically provides two Initially Unix was a command


GUIs, KDE and Gnome. But based OS, but later a GUI was
there are millions of created called Common
alternatives such as LXDE, Desktop Environment. Most
Xfce, Unity, Mate, twm, ect. distributions now ship with
Gnome.

File system support Ext2, Ext3, Ext4, Jfs, jfs, gpfs, hfs, hfs+, ufs, xfs, zfs
ReiserFS, Xfs, Btrfs, FAT, format
FAT32, NTFS

BASH (Bourne Again SHell) Originally the Bourne Shell.


Text mode interface is the Linux default shell. It Now it's compatible with
can support multiple many others including BASH,
command interpreters. Korn & C.
Price Free but support is available Some free for development
for a price. use (Solaris) but support is
available for a price.

Security Linux has had about 60-100 A rough estimate of UNIX


viruses listed till date. None of viruses is between 85 -120
them actively spreading viruses reported till date
nowadays.

Threat detection and In case of Linux, threat Because of the proprietary


solution detection and solution is very nature of the original Unix,
fast, as Linux is mainly users have to wait for a while,
community driven and to get the proper bug fixing
whenever any Linux user patch. But these are not as
posts any kind of threat, common.
several developers start
working on it from different
parts of the world

Processors Dozens of different kinds. x86/x64, Sparc, Power,


Itanium, PA-RISC, PowerPC
and many others.

Examples Ubuntu,Fedora,Red Hat, OS X, Solaris, All Linux


Debian, Archlinux,Android
etc.

Originally developed for is available on PA-RISC and


Intel's x86 hardware, ports Itanium machines. Solaris also
available for over two dozen available for x86/x64 based
Architectures CPU types including ARM systems.OSX is
Inspired by MINIX (a Unix- PowerPC(10.0-
like system) and eventually 10.5)/x86(10.4)/x64(10.5-
after adding many features of 10.8)
GUI, Drivers etc, Linus

Torvalds developed the In 1969, it was developed by a


framework of the OS that group of AT&T employees at
became LINUX in 1992. The Bell Labs and Dennis Ritchie.
LINUX kernel was released It was written in C language
on 17th September, 1991 and was designed to be a
Inception portable, multi-tasking and
multi-user system in a time-
sharing configuration
UNIX Operating System Names
A few popular names:
1. HP-UX
2. IBM AIX
3. Sun Solairs
4. Mac OS X
5. IRIX

Linux Distribution (Operating System) Names


A few popular names:
1. Redhat Enterprise Linux
2. Fedora Linux
3. Debian Linux
4. Suse Enterprise Linux
5. Ubuntu Linux

Common Things Between Linux & UNIX


Both share many common applications such as:
1. GUI, file, and windows managers (KDE, Gnome)
2. Shells (ksh, csh, bash)
3. Various office applications such as OpenOffice.org
4. Development tools (perl, php, python, GNU c/c++ compilers)
5. Posix interface
Difference between Linux and Windows

Linux Windows

What is it? Linux is an example of Open Windows is the family of


Source software development operating system (OS) from
and Free Operating System Microsoft, which is the most
(OS). famous OS in the world.

Cost Linux can be freely For desktop or home use,


distributed, downloaded Windows can be expensive. A
freely, distributed through single copy can cost around
magazines, Books etc. There $50 to $ 450 depending on the
are priced versions for Linux version of Windows
also, but they are normally
cheaper than Windows.

User Everyone. From home users to Everyone. From home users to


developers and computer developers and computer
enthusiasts alike. enthusiasts alike.

Manufacturer Linux kernel is developed by Microsoft created the


the community. Linus Windows operating system,
Torvalds oversees things. but allows other computer
manufactures to distribute
their own computers with
Windows pre-installed.

Usage Linux can be installed on a On PC's desktops, laptops,


wide variety of computer servers and some phones.
hardware, ranging from
mobile phones, tablet
computers and video game
consoles, to mainframes and
supercomputers.

Development and Linux is developed by Open Windows is developed and


Distribution Source development i.e. distributed by Microsoft.
through sharing and
collaboration of code and
features through forums etc
and it is distributed by various
vendors.
GUI Linux typically provides two The Windows GUI is an
GUIs, KDE and Gnome. But integral component of the OS
there are millions of and is not replaceable. This
alternatives such as LXDE, can be a con when it comes to
Xfce, Unity, Mate, twm, ect. Windows 8's Metro

File system support Ext2, Ext3, Ext4, Jfs, FAT32, NTFS, exFAT
ReiserFS, Xfs, Btrfs, FAT,
FAT32, NTFS FAT

Text mode interface BASH (Bourne Again SHell) Windows uses a command
is the Linux default shell. It shell and each version of
can support multiple Windows has a single
command interpreters. command interpreter with dos-
like commands, recently there
is the addition of the optional
PowerShell that uses more
Unix-like commands.

Price Free but support is available $50-$450


for a price.

Security Linux has had about 60-100 According to Dr. Nic Peeling
viruses listed till date. None of and Dr Julian Satchell's
them actively spreading Analysis of the Impact of
nowadays. Open Source Software there
have been more than 60,000
viruses in Windows. Anti
Virus cost about $20 to $400

Threat detection and In case of Linux, threat After detecting a major threat
solution detection and solution is very in Windows OS, Microsoft
fast, as Linux is mainly generally releases a patch that
community driven and can fix the problem and it can
whenever any Linux user take more than 2/3 months.
posts any kind of threat, Sometimes sooner, Microsoft
several developers start releases patches and updates
working on it from different weekly.
parts of the world

Processors Dozens of different kinds. Limited but most (80%)

Examples Ubuntu, Fedora, Red Hat, Windows 8, 8.1, 7, Vista, XP


Debian, Archlinux, Android
etc.

Gaming Very few games available Almost all games are


natively. Some games can be compatible with Windows.
played through Wine, but Some CPU intensive and
often not all features are graphics intensive games are
available. exclusive to Windows PC's.

User experience Although there are many GUI Everything can be controlled
applications, most of the work through GUI and
is done through Terminal (a incompatibility problems are
console window), and if a rare
problem arrises GUI is rarely
usable to fix them.

Graphics performance Because hardware Combined with newest


manufacturers, such as DirectX versions and full
NVidia, often does not provide graphics card support the
documentation for linux performance is almost as good
developers, drivers can not use as it can get.
full card performance.

Company / developer Linus Torvalds Microsoft

Introduction (from Linux is a Unix-like and Microsoft Windows is a series


Wikipedia) POSIX-compliant computer of graphical interface
operating system assembled operating systems developed,
under the model of free and marketed, and sold by
open source software Microsoft. Microsoft
development and distribution. introduced an operating
The defining component of environment named Windows
Linux is the Linux kernel, an on November 20, 1985 as a
operating system kernel first graphical operating system
released shell for MS-DOS.

All PowerPC: versions 1.0 - NT


4.0; DEC Alpha: versions 1.0 -
Supported platforms NT 4.0; MIPS R4000:
versions 1.0 - NT 4.0; IA-32:
versions 1.0 - 8; IA-64:
version XP; x86-64: versions
XP - 8; ARM: version RT;

Source model Open Source Closed / Shared source

Terminal Multi Terminal Windows --------

Components of Linux System


Linux Operating System has primarily three components
Kernel - Kernel is the core part of Linux. It is responsible for all major activities of this
operating system. It is consists of various modules and it interacts directly with the underlying
hardware. Kernel provides the required abstraction to hide low level hardware details to
system or application programs.
System Library - System libraries are special functions or programs using which application
programs or system utilities accesses Kernel's features. These libraries implements most of the
functionalities of the operating system and do not requires kernel module's code access rights.
System Utility - System Utility programs are responsible to do specialized, individual level
tasks.
Kernel Mode vs User Mode
Kernel component code executes in a special privileged mode called kernel mode with full access to
all resources of the computer. This code represents a single process, executes in single address space
and do not require any context switch and hence is very efficient and fast. Kernel runs each processes
and provides system services to processes, provides protected access to hardwares to processes.
Support code which is not required to run in kernel mode is in System Library. User programs and
other system programs works in User Mode which has no access to system hardwares and kernel
code. User programs/ utilities use System libraries to access Kernel functions to get system's low level
tasks.

Basic Features
Following are some of the important features of Linux Operating System.
Portable - Portability means softwares can works on different types of hardwares in same
way.Linux kernel and application programs supports their installation on any kind of hardware
platform.
Open Source - Linux source code is freely available and it is community based development
project. Multiple teams works in collaboration to enhance the capability of Linux operating
system and it is continuously evolving.
Multi-User - Linux is a multiuser system means multiple users can access system resources
like memory/ ram/ application programs at same time.
Multiprogramming - Linux is a multiprogramming system means multiple applications can
run at same time.
Hierarchical File System - Linux provides a standard file structure in which system files/ user
files are arranged.
Shell - Linux provides a special interpreter program which can be used to execute commands
of the operating system. It can be used to do various types of operations, call application
programs etc.
Security - Linux provides user security using authentication features like password protection/
controlled access to specific files/ encryption of data.

Architecture

Linux System Architecture is consists of following layers


Hardware layer - Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).

Kernel - Core component of Operating System, interacts directly with hardware, provides low
level services to upper layer components.
Shell - An interface to kernel, hiding complexity of kernel's functions from users. Takes
commands from user and executes kernel's functions.
Utilities - Utility programs giving user most of the functionalities of an operating systems.

What is finger?
finger command is used to lookup information about an user.
Syntax
finger [-lmsp] [user1 user2 .. ]

1. View detail about a particular user


finger command will display login, username, home directory, shell information about a particular
user as shown below.
$ finger sathiya
Login: sathiya Name: (null)
Directory: /home/sathiya Shell: /bin/bash
On since Mon Nov 1 18:45 (IST) on :0 (messages off)
On since Mon Nov 1 18:46 (IST) on pts/0 from :0.0
New mail received Fri May 7 10:33 2010 (IST)
Unread since Sat Jun 7 12:59 2008 (IST)
No Plan.

2. View login details and Idle status about an user


You can use finger -s option to view the login detail for a particular user.
$ finger -s root
Login Name Tty Idle Login Time Office Office Phone
root root *1 19d Wed 17:45
root root *2 3d Fri 16:53
root root *3 Mon 20:20
root root *ta 2 Tue 15:43
root root *tb 2 Tue 15:44

Syntax and Options


Short
Option Description
Option

Display the users login name, real name, terminal name and write status idle time,
-s login time, and either

office location and office phone number, or the remote host.


Prevent the -l option of finger from displaying the contents of the .forward, .plan,
-p .project and .pubkey

files.
Prevent matching of user names. User is usually a login name; however, matching will
also be done on the users

-m real names, unless the -m option is supplied.Display the users login name, real name,
terminal name and write
status idle time, login time, and either office location and office phone number, or the
remote host.
When used in conjunction with the -s option, the office location and office phone
-o information is displayed

instead of the name of the remote host.

SYNOPSIS
finger [-lmsp ] [user ... ] [user@host ... ]

Options are:
-s
Finger displays the user's login name, real name, terminal name and write status
(as a ``*'' after the terminal name if write permission is denied), idle time, login
time, office location and office phone number.

Login time is displayed as month, day, hours and minutes, unless more than six months ago, in
which case the year is displayed rather than the hours and minutes.
Unknown devices as well as nonexistent idle and login times are displayed as single asterisks.
-l

Produces a multi-line format displaying all of the information described for the -s
option as well as the user's home directory, home phone number, login shell, mail
status, and the contents of the files ``.plan '' ``.project '' ``.pgpkey '' and
``.forward '' from the user's home directory.

Phone numbers specified as eleven digits are printed as ``+N-NNN-NNN-NNNN''. Numbers


specified as ten or seven digits are printed as the appropriate subset of that string. Numbers
specified as five digits are printed as ``xN-NNNN''. Numbers specified as four digits are
printed as ``xNNNN''.
If write permission is denied to the device, the phrase ``(messages off)'' is appended to the line
containing the device name. One entry per user is displayed with the -l option; if a user is
logged on multiple times, terminal information is repeated once per login.
Mail status is shown as ``No Mail.'' if there is no mail at all, ``Mail last read DDD MMM ##
HH:MM YYYY (TZ)'' if the person has looked at their mailbox since new mail arriving, or
``New mail received ...'', `` Unread since ...'' if they have new mail.
-p

Prevents the -l option of finger from displaying the contents of the ``.plan ''
``.project '' and ``.pgpkey '' files.

-m

Prevent matching of user names. User is usually a login name; however, matching
will also be done on the users' real names, unless the -m option is supplied. All
name matching performed by finger is case insensitive.

If no options are specified, finger defaults to the -l style output if operands are provided, otherwise to
the -s style. Note that some fields may be missing, in either format, if information is not available for
them.
If no arguments are specified, finger will print an entry for each user currently logged into the system.
Finger may be used to look up users on a remote machine. The format is to specify a user as
``user@host '' or ``@host '' where the default output format for the former is the -l style, and the
default output format for the latter is the -s style. The -l option is the only option that may be passed to
a remote machine.
If standard output is a socket, finger will emit a carriage return (^M) before every linefeed (^J). This
is for processing remote finger requests when invoked by fingerd(8).
The Linux finger command displays information about the system users. We can view all information
about user if we know the user account login name. Below are some examples of the Linux finger
command with useful options that you can use to view user information.
Type 'finger' at the command prompt without any option will give an output of users currently log in
the system:
bill@slackware:~$ finger
Login Name Tty Idle Login Time Office Office Phone
bill billy jadon tty1 Apr 10 13:38
root tty2 Apr 10 14:38
bill@slackware:~$

The output is the same if we issue Linux finger command with -s option, but this time we are looking
at a specific user:
bill@slackware:~$ finger -s bill
Login Name Tty Idle Login Time Office Office Phone
bill billy jadon tty1 Apr 10 13:38
bill@slackware:~$

This is what each column means:


The column Login is user's login name.

The column Name is user's full name.

The column Tty is terminal user's login in.

The column Idle shows idle time.

The column Login Time shows date and time when user login in.

The column Office shows user's office location.

The column Office Phone shows user's office phone number.

Now, try Linux finger command with -l option:


bill@slackware:~$ finger -l bill
Login: bill Name: billy jadon
Directory: /home/bill Shell: /bin/bash
On since Mon Apr 10 13:38 (MYT) on tty1
No mail.
No Plan.
bill@slackware:~$

When Linux finger command is issued with -l option, it produces a multi-line format displaying the
same result as -s with extra user's home directory, home phone number, shell, mail status, and the
contents of the files ``.plan'', ``.project'', ``.pgpkey'' and ``.forward'' from the user's home directory.
Remember that the Linux finger command also can be a threat to the Linux system if not properly
secured. Attacker can just guess a username and with information gains from finger command, it just a
matter of time before your system being compromised. If you can live without the finger command,
just disable the daemon.
n Linux operating system, you can simply check the information of any user from remote or local
command line interface. That is finger command. To use this command, your Linux machine need
have finger utility installed on it. This feature is a very basic with Linux system, so you can easily
find install package proper with you Linux system. This article will focus on usage of finger
command and its options with demonstration command run on Ubuntu Linux.
Syntax
finger [-lmsp] [user1 user2 .. ]

Finger command with option -s


With option s finger displays the users login name, real name, terminal name and write status ( the
asterisk before terminal name mean that you dont have write permission with that device ), idle time,
login time, office location and office phone number. The login time is displayed with format MM DD
HH:mm. If the time exceeds six months, the year is displayed rather than the hours and minutes.
Unknown devices as well as nonexistent idle and login times are displayed as single asterisk.
Finger command with option -l
The option l follow the finger command with produces a multi-line format displaying all of the
information described for the -s option as well as the users home directory, home phone number,
login shell, mail status, and the contents of the files .plan, .project, .pgpkey and .forward from
the users home directory.

The phrase (messages off) mean that user harry dont have write permission to root on the
devices pts/4 and pts/7. One entry per user is displayed with the l option; if a user is logged on
multiple times, terminal information is repeated once per login.
Mail status is shown as No Mail. if there is no mail at all, Mail last read DDD MMM ## HH:MM
YYYY (TZ) if the person has looked at their mailbox since new mail arriving, or New mail received
, Unread since if they have new mail.
Finger command with option -p
The option p is completely same with option l, except it doesnt include.plan, .project and
.pgpkey files of users in returned result.

Finger command with option -m


With the option m finger will prevent matching of user names in returned result. User is usually a
login name; however, matching will also be done on the users real names, unless the -m option is
supplied. All name matching performed by finger is case insensitive. For example, our system has two
users named harry and harry1. Without option m, finger will return information of both users
and only return information of user harry if there m follow.
With option -m
Without option -m
If no options are specified, finger defaults to the -l style output if operands are provided, otherwise to
the -s style. Note that some fields may be missing, in either format, if information is not available for
them.
If no arguments are specified, finger will print an entry for each user currently logged into the system.
- See more at: http://linoxide.com/linux-command/finger-command-user-
details/#sthash.XsZAQ2LU.dpuf

w (Unix)
The command w on many Unix-like operating systems provides a quick summary of
every user logged into a computer, [1] what that user is currently doing, and what load all
the activity is imposing on the computer itself. The command is a one-command
combination of several other Unix programs: who, uptime, and ps -a.

Example
Sample output (this may vary between systems):
$ w
11:12am up 608 day(s), 19:56, 6 users, load average: 0.36, 0.36, 0.37
User tty login@ idle what
smithj pts/5 8:52am w
jonesm pts/23 20Apr06 28 -bash
harry pts/18 9:01am 9 pine
peterb pts/19 21Apr06 emacs -nw html/index.html
janetmcq pts/8 10:12am 3days -csh
singh pts/12 16Apr06 5:29 /usr/bin/perl -w perl/test/program.pl

This command shows who is logged on and what they are doing.
Description:
w displays information about the users currently on the machine, and their processes. The header
shows, in this order, the current time, how long the system has been running, how many users are
currently logged on, and the system load averages for the past 1, 5, and 15 minutes.
The following entries are displayed for each user: login name, the tty name, the remote host, login
time, idle time, JCPU, PCPU, and the command line of their current process.
The JCPU time is the time used by all processes attached to the tty. It does not include past
background jobs, but does include currently running background jobs.
The PCPU time is the time used by the current process, named in the what field.
Synopsis :
w -[husifV] [user]
Options:
-h
Dont print the header.
-u
Ignores the username while figuring out the current process and cpu times. To demonstrate this, do a
su and do a w and a w -u.
-s
Use the short format. Dont print the login time,JCPU or PCPU times.
-f
Toggle printing the from (remote hostname) field. The default as released is for the from field to not
be printed, although your system administrator or distribution maintainer may have compiled a
version in which the from field is shown by default.
-i
Display IP address instead of hostname (if possible)
-V
Display version information.
user
Show information about the specified user only.
Examples :
$ w
00:58:14 up 3 min, 2 users, load average: 0.56, 0.41, 0.18
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
username tty7 Sun03 21:09m 4.54s 0.21s gnome-session -
username pts/0 :0 Sun03 0.00s 0.21s 0.00s w

$ w -s
10:16:04 up 13 min, 2 users, load average: 0.08, 0.15, 0.20
USER TTY FROM IDLE WHAT
mohakkat tty7 :0 11:15m gnome-session --session=ubuntu
mohakkat pts/2 :0 11:14m w -s
$ w -h
mohakkat tty7 :0 23:01 11:15m 3.78s 0.19s gnome-session -
mohakkat pts/2 :0 23:01 11:14m 0.08s 0.00s w -h

About w
The w command is a quick way to see who is logged on and what they are doing.

Syntax
w [options] user [...]

Description
w displays information about the users currently on the machine, and their processes.

The header of the the output shows (in this order): the current time, how long the system has been
running, how many users are currently logged on, and the system load averages for the past 1, 5, and
15 minutes.

The following entries are displayed for each user: login name, the tty name, the remote host they are
logged in from, the amount of time they have been logged in, their idle time, JCPU, PCPU, and the
command line of their current process.

The JCPU time is the time used by all processes attached to the tty. It does not include past
background jobs, but does include currently running background jobs.

The PCPU time is the time used by the current process, named in the "what" field.

Options
-h, --no-
Don't print the header.
header

Ignores the username while figuring out the current process and cpu times. (To
-u, --no-
see an example of this, switch to the root user with "su" and then run both "w"
current
and "w -u".)

-s,
Display abbreviated output (don't print the login time, JCPU or PCPU times).
--short

Toggle printing the from (remote hostname) field. The default as released is for
-f, the from field to not be printed, although your system administrator or
--from distribution maintainer may have compiled a version in which the from field is
shown by default.

--help Display a help message, and exit.

-V,
--versio Display version information, and exit.
n

-o, Old style output (prints blank space for idle times less than one minute).
--old-
style

user Show information about the specified user user only.

Environment
PROCPS_USER The value of this environment variable, if set, will override the default
LEN width (8) of the username column.

PROCPS_FRO The value of this environment variable, if set, will override the default
MLEN width (16) of the from column.

Files
/
This file stores the information about who is
var/run/ut
currently logged on.
mp

/proc System process information.

Examples
w
Running the w command with no arguments will show a list of logged on users and their processes.
w chope
Show information for the user named chope.

About who
Displays who is logged on to the system.
Syntax
who [ OPTION ]... [ FILE ] [ am i ]
Description
The who command prints information about all users who are currently logged in.
Options
-a, --all Same as using the options -b -d --login -p -r -t -T -u.

-b,
Display the time of the last system boot.
--boot

-d,
Display dead processes.
--dead

-H,
--headin Print a line of column headings.
g

Print IP addresses instead of hostnames. with --lookup, canonicalizes based on


--ips
stored IP, if available, rather than stored hostname.
-l,
Print system login processes.
--login

--lookup Attempt to canonicalize hostnames via DNS.

Only print information about the user and host associated with standard input
-m (the terminal where the command was issued). This method adheres to the
POSIX standard.

-p,
--proces Print active processes spawned by init.
s

-q,
Displays all login names, and a count of all logged-on users.
--count

-r,
--runlev Print the current runlevel.
el

-s,
Print only name, line, and time fields. This is the default.
--short

-t, Print the last time the system clock was changed, if the information is
--time available.

-T, -w, Add a character which indicates the state of the terminal line: "+" if the
--mesg terminal is writable, "-" if it is not, or "?" if a bad line is encountered.

-u,
Print the idle time for each user, and the process ID.
--users

--
messag Same as -T.
e

--
Same as -T.
writable

--help Display a help message, and exit.

--
Display version information, and exit.
version

Linux / Unix Command: w

Command Library

NAME
w - show who is logged on and what they are doing
SYNOPSIS
w - [-husfV] [user]

DESCRIPTION
w displays information about the users currently on the machine, and their processes.
The header shows, in this order, the current time, how long the system has been
running, how many users are currently logged on, and the system load averages for the
past 1, 5, and 15 minutes.

The following entries are displayed for each user: login name, the tty name, the remote host, login
time, idle time, JCPU, PCPU, and the command line of their current process.
The JCPU time is the time used by all processes attached to the tty. It does not include past
background jobs, but does include currently running background jobs.
The PCPU time is the time used by the current process, named in the "what" field.

COMMAND-LINE OPTIONS
-h

Don't print the header.

-u

Ignores the username while figuring out the current process and cpu times. To
demonstrate this, do a "su" and do a "w" and a "w -u".

-s

Use the short format. Don't print the login time, JCPU or PCPU times.

-f

Toggle printing the from (remote hostname) field. The default if for the from field
to be printed, although your system administrator or distribution maintainer may
have compiled a version in which the from field is not shown by default.

-V

Display version information.

user

Show information about the specified user only.

WHO
About who
Displays who is logged on to the system.
Syntax
who [ OPTION ]... [ FILE ] [ am i ]
Description
The who command prints information about all users who are currently logged in.
Options
-a, --all Same as using the options -b -d --login -p -r -t -T -u.

-b,
Display the time of the last system boot.
--boot

-d,
Display dead processes.
--dead

-H,
--headin Print a line of column headings.
g

Print IP addresses instead of hostnames. with --lookup, canonicalizes based on


--ips
stored IP, if available, rather than stored hostname.

-l,
Print system login processes.
--login

--lookup Attempt to canonicalize hostnames via DNS.

Only print information about the user and host associated with standard input
-m (the terminal where the command was issued). This method adheres to the
POSIX standard.

-p,
--proces Print active processes spawned by init.
s

-q,
Displays all login names, and a count of all logged-on users.
--count

-r,
--runlev Print the current runlevel.
el

-s,
Print only name, line, and time fields. This is the default.
--short

-t, Print the last time the system clock was changed, if the information is
--time available.

-T, -w, Add a character which indicates the state of the terminal line: "+" if the
--mesg terminal is writable, "-" if it is not, or "?" if a bad line is encountered.

-u,
Print the idle time for each user, and the process ID.
--users
--
messag Same as -T.
e

--
Same as -T.
writable

--help Display a help message, and exit.

--
Display version information, and exit.
version

Notes
If FILE is specified, who gathers its information from this file. Otherwise, it reads from a default file
location (usually /var/run/utmp).

If the arguments "am i" are specified, who assumes the -m option.
Examples
who
Displays the username, line, and time of all currently logged-in sessions. For example:
lucy pts/1 2014-01-17 22:42 (:0.0)
psmith pts/2 2014-01-18 09:30 (:0.0)
alan pts/3 2013-12-25 08:52 (:0.0)
neil pts/4 2014-01-05 15:33 (:0.0)
martha pts/0 2013-09-04 22:05 (:0.0)
who am i
Displays the same information, but only for the terminal session where the command was issued, for
example:
alan pts/3 2013-12-25 08:52 (:0.0)
who -aH
Displays "all" information, and headers above each column of data, for example:
NAME LINE TIME IDLE PID COMMENT EXIT
2014-01-17 07:00 154 id=si term=0 exit=0
system boot 2014-01-17 07:00
run-level 2 2014-01-17 07:00 last=S
2014-01-17 07:01 1607 id=l2 term=0 exit=0
LOGIN tty6 2014-01-17 07:01 2809 id=6
LOGIN tty5 2014-01-17 07:01 2808 id=5
LOGIN tty4 2014-01-17 07:01 2807 id=4
LOGIN tty2 2014-01-17 07:01 2805 id=2
LOGIN tty1 2014-01-17 07:01 2804 id=1
LOGIN tty3 2014-01-17 07:01 2806 id=3
pts/0 2014-01-17 11:31 2811 id=ts/0 term=0 exit=0
lucy + pts/1 2014-01-17 22:42 . 6609 (:0.0)
pts/2 2014-01-18 02:14 0 id=/2 term=0 exit=0
pts/3 2014-01-18 02:08 0 id=/3 term=0 exit=0
pts/4 2014-01-17 21:30 0 id=/4 term=0 exit=0
lucy + pts/0 2014-01-17 22:01 01:04 6330 (:0.0)

As a Linux user, sometimes it is required to know some basic information like :


Time of last system boot

List of users logged-in

Current run level etc


Though this type of information can be obtained from various files in the Linux system
but there is a command line utility 'who' that does exactly the same for you. In this
article, we will discuss the capabilities and features provided by the 'who' command.

The basic syntax of the who command is :

who [OPTION]... [ FILE | ARG1 ARG2 ]

Examples of 'who' command

1. Get the information on currently logged in users


This is done by simply running the 'who' command (without any options). Consider the
following example:

$ who
himanshu tty7 2012-08-07 05:33 (:0)
himanshu pts/0 2012-08-07 06:47 (:0.0)
himanshu pts/1 2012-08-07 07:58 (:0.0)

2. Get the time of last system boot


The is done using the -b option. Consider the following example:

$ who -b
system boot 2012-08-07 05:32
So we see that the above output gives the exact date and time of last system boot.

3. Get information on system login processes


This is done using the -l option. Consider the following example:

$ who -l
LOGIN tty4 2012-08-07 05:32 1309 id=4
LOGIN tty5 2012-08-07 05:32 1313 id=5
LOGIN tty2 2012-08-07 05:32 1322 id=2
LOGIN tty3 2012-08-07 05:32 1324 id=3
LOGIN tty6 2012-08-07 05:32 1327 id=6
LOGIN tty1 2012-08-07 05:32 1492 id=1
So we see that information related to system login processes was displayed in the
output.

4. Get the hostname and user associated with stdin


This is done using the -m option. Consider the following example:
$ who -m
himanshu pts/1 2012-08-07 07:58 (:0.0)
So we see that the relevant information was produced in the output.

5. Get the current run level


This is done using the -r option. Consider the following example:

$ who -r
run-level 2 2012-08-07 05:32
So we see that the information related to current run level (which is 2) was produced in
the output.

6. Get the list of user logged in


This is done using the -u option. Consider the following example:

$ who -u
himanshu tty7 2012-08-07 05:33 old 1619 (:0)
himanshu pts/0 2012-08-07 06:47 00:31 2336 (:0.0)
himanshu pts/1 2012-08-07 07:58 . 2336 (:0.0)
So we see that a list of logged-in users was produced in the output.

7. Get number of users logged-in and their user names


This is done using the -q option. Consider the following example:

$ who -q
himanshu himanshu himanshu
# users=3
So we see that information related to number of logged-in users and their user names
was produced in the output.

8. Get all the information


This is done using the -a option. Consider the following example:

$ who -a
system boot 2012-08-07 05:32
run-level 2 2012-08-07 05:32
LOGIN tty4 2012-08-07 05:32 1309 id=4
LOGIN tty5 2012-08-07 05:32 1313 id=5
LOGIN tty2 2012-08-07 05:32 1322 id=2
LOGIN tty3 2012-08-07 05:32 1324 id=3
LOGIN tty6 2012-08-07 05:32 1327 id=6
LOGIN tty1 2012-08-07 05:32 1492 id=1
himanshu + tty7 2012-08-07 05:33 old 1619 (:0)
himanshu + pts/0 2012-08-07 06:47 . 2336 (:0.0)
himanshu + pts/1 2012-08-07 07:58 . 2336 (:0.0)
So we see that all the information that 'who' can print is produced in output.
Linux / Unix: who Command Examples To List Users on
The Systems
by Nix Craft on January 27, 2013 0 comments LAST UPDATED January 27, 2014
in Commands, Linux, UNIX

I am a new Linux and Unix system user. How do I display who is logged on my Linux or Unix-like
operating system using shell prompt?

You need to use who command to display users who are currently logged in your server.
who command
details

Find who is on the


Description
system

Category User Information

Difficulty Easy

Root privileges No

Estimated completion
5m
time

Contents

Syntax

Examples

Show list of user logged in

Find time of last boot

List dead processes

List login processes

Count all login names

Show current runlevel

Show all info about logged on users

Options
Video

See also
This command is useful to find out the following information:

1. Time of last system boot.

2. Current run level.

3. List of logged in users and more.

Purpose
Display who is on the system.

Syntax
The basic syntax is as follows:
who
who am i
who [options] [File]
who --help
who --version
who | grep 'userNameHere'

Where,
If no non-options provided, who displays the following information for each user
currently logged on:

o login name

o terminal line

o login time

o remote hostname or X display

If you give one non-option argument, who uses that instead of a default system-
maintained file such s /var/run/utmp as the name of the file containing the record
of users logged on.

If given two non-option arguments, who prints only the entry for the user running
it preceded by the hostname. Traditionally, the two arguments given are 'am i', as
in 'who am i'.

who command examples


To show a list of all the users currently logged in to the system, type:
$ who
Sample outputs:
Fig. 01: Identifying who is logged on your server

The sample output in this example shows that the user vivek is logged in on pts/0, and
has been on since 14:10 on 27 January. To display line of column headings pass the -H
option:
$ who -H
To show only hostname and user associated with stdin (usually keyboard), enter:
$ who -m
To show active processes spawned by init:
$ who -p
To show user's message status as +, - or ?, enter:
$ who -T

Show or list users logged in


Type the command:
$ who -u

Show time of last system boot


To display time of last system boot pass the -b option to who command:
$ who -b
Sample outputs:
system boot 2014-01-05 10:02
The output in this example, shows that the system was booted since 10:02 on 05 January.
Show dead processes on the system
You need pass the -d option to who command:
$ who -d
OR
$ who -d -H
Sample outputs:
NAME LINE TIME IDLE PID COMMENT EXIT
pts/1 2014-01-11 09:17 56094 id=ts/1 term=0 exit=0
pts/2 2014-01-05 15:46 11070 id=ts/2 term=0 exit=0
pts/2 2014-01-08 03:31 3614 id=/2 term=0 exit=0
pts/1 2014-01-11 16:54 64559 id=/1 term=0 exit=0
pts/3 2014-01-11 17:13 15818 id=/3 term=0 exit=0
pts/4 2014-01-25 11:02 46807 id=ts/4 term=0 exit=0

Show system login processes


To just display system login processes pass the -l option:
$ who -l
OR
$ who -l -H
Sample outputs:
NAME LINE TIME IDLE PID COMMENT
LOGIN tty2 2014-01-05 10:03 8750 id=2
LOGIN tty1 2014-01-05 10:03 8748 id=1
LOGIN tty3 2014-01-05 10:03 8752 id=3
LOGIN /dev/ttyS1 2014-01-05 10:03 8747 id=v/tt
LOGIN tty4 2014-01-05 10:03 8754 id=4
LOGIN tty5 2014-01-05 10:03 8756 id=5
LOGIN tty6 2014-01-05 10:03 8758 id=6

Count all login names and number of users logged on the system
To count all login names and number of users logged on:
$ who -q
Sample outputs:

Fig.02: Displaying and counting all users logged on

Display the current runlevel


To display the current system runlevel, type:
$ who -r
Sample outputs:
run-level 3 2014-01-05 10:02
You can combine -r and -b options as follows:
$ who -r -b
Sample outputs:
system boot 2014-01-05 10:02
run-level 3 2014-01-05 10:02

Display all
The -a is same as same as -bdprtTu options as discussed earlier:
Sample outputs:
NAME LINE TIME IDLE PID COMMENT EXIT
system boot 2014-01-05 10:02
run-level 3 2014-01-05 10:02
LOGIN tty2 2014-01-05 10:03 8750 id=2
LOGIN tty1 2014-01-05 10:03 8748 id=1
LOGIN tty3 2014-01-05 10:03 8752 id=3
LOGIN /dev/ttyS1 2014-01-05 10:03 8747 id=v/tt
LOGIN tty4 2014-01-05 10:03 8754 id=4
LOGIN tty5 2014-01-05 10:03 8756 id=5
LOGIN tty6 2014-01-05 10:03 8758 id=6
root + pts/0 2014-01-27 03:37 . 11149 (10.1.6.120)
pts/1 2014-01-11 09:17 56094 id=ts/1 term=0 exit=0
pts/2 2014-01-05 15:46 11070 id=ts/2 term=0 exit=0
pts/2 2014-01-08 03:31 3614 id=/2 term=0 exit=0
pts/1 2014-01-11 16:54 64559 id=/1 term=0 exit=0
pts/3 2014-01-11 17:13 15818 id=/3 term=0 exit=0
pts/4 2014-01-25 11:02 46807 id=ts/4 term=0 exit=0

who command options


Optio
Description
n

-a Same as -b -d --login -p -r -t -T -u

-b Time of last system boot

-d Print dead processes

-H Print line of column headings

-l Print system login processes

Only hostname and user associated


-m
with stdin

-p Print active processes spawned by init

All login names and number of users


-q
logged on

-r Print current runlevel

-t Print last system clock change

-T Add user's message status as +, - or ?


-u List users logged in

Linux who command shows who is logged on to the system. This is a useful command for a Linux
system administrator because they can check how many users currently logged in the system and who
they are. The Linux who command offers some options that user can use to see more details about
users such as login time, terminal used and process id. However that is not the only things the who
command can do. We can also use Linux who command to check when was the Linux system last
booted and the current system's run level.

Linux who command examples


We already know what Linux who command can do, now it's time to see some examples. Below are
the Linux who command examples run with options regularly used by system administrator.
Probably the well known Linux who command's option is the am i. When invoke who am i from a
Linux command line terminal (and unix as well), the who command prints only the information about
user who runs the command.
luzar@ubuntu:~$ who am i
luzar pts/0 2009-07-06 22:39 (:0.0)

When we run who with no option in Linux command line terminal, we'll get the result similar to the
example below:
luzar@ubuntu:~$ who
root tty1 2009-07-06 22:06
luzar tty7 2009-07-06 19:17 (:0)
luzar pts/0 2009-07-06 21:28 (:0.0)

The example above shows two users logged in the Linux system. We can see current users in the
system's username are root who logged in tty1 and luzar who's using terminal 7 (tty7), which we
know it's the x-window system. The other terminal is pts/0 also by a user named luzar, which means
he opened a terminal from x-window. We also see the complete date and time they logged into the
Linux system in tty1, tty7 and even when they opened a command line terminal from x-window. So,
when we invoke Linux who command without any option, it prints login name, terminal line, login
time, and remote hostname or X display information.
Linux who -l command example:
luzar@ubuntu:~$ who -l
LOGIN tty3 2009-07-06 19:17 4439 id=3
LOGIN tty5 2009-07-06 19:17 4432 id=5
LOGIN tty4 2009-07-06 19:17 4431 id=4
LOGIN tty6 2009-07-06 19:17 4441 id=6
LOGIN tty2 2009-07-06 19:17 4438 id=2

Linux who command print system login processes. Don't get confuse with this option. When running
who -l, 'who' list only the entries that correspond to processes via which the system is waiting for a
user to login. The user name is always LOGIN.
Linux who -m command example:
luzar@ubuntu:~$ who -m
luzar pts/0 2009-07-06 21:28 (:0.0)

The Linux who -m command prints only hostname and user associated with stdin. It the same as
running who am i command.
Linux who -q command example:
luzar@ubuntu:~$ who -q
root luzar luzar
# users=3

The Linux who -q command prints all login names and the number of users logged on. Using -q
option will overrides all other options.
Linux who -r command example:
luzar@ubuntu:~$ who -r
run-level 2 2009-07-06 19:17 last=

The Linux who -r command prints system's current runlevel.


Linux who -T command example:
luzar@ubuntu:~$ who -T
root - tty1 2009-07-06 22:06
luzar + tty7 2009-07-06 19:17 (:0)
luzar + pts/0 2009-07-06 21:28 (:0.0)

After each login name, Linux who -T command prints a character indicating the user's message status,
which:
+ means allowing `write' messages.

- means disallowing `write' messages.

? means cannot find terminal device.

Linux who -u command example:


luzar@ubuntu:~$ who -u
root tty1 2009-07-06 22:06 00:07 5465
luzar tty7 2009-07-06 19:17 old 5506 (:0)
luzar pts/0 2009-07-06 21:28 . 6509 (:0.0)

The Linux who -u command lists users logged in. After the login time, the who command prints the
number of hours and minutes that the user has been idle.
. means the user was active in the last minute.

old means the user has been idle for more than 24 hours.

Linux who -b command example:


luzar@ubuntu:~$ who -b
system boot 2009-07-06 19:17

The Linux who -b command prints the date and time of last system boot.
Linux who -a command example:
luzar@ubuntu:~$ who -a
system boot 2009-07-06 19:17
run-level 2 2009-07-06 19:17 last=
LOGIN tty3 2009-07-06 19:17 4439 id=3
LOGIN tty5 2009-07-06 19:17 4432 id=5
LOGIN tty4 2009-07-06 19:17 4431 id=4
LOGIN tty6 2009-07-06 19:17 4441 id=6
LOGIN tty2 2009-07-06 19:17 4438 id=2
root - tty1 2009-07-06 22:06 00:32 5465
luzar + tty7 2009-07-06 19:17 old 5506 (:0)
luzar + pts/0 2009-07-06 22:39 . 6938 (:0.0)

The Linux who -a command is the same as invoke who -b -d --login -p -r -t -T -u.
Linux / Unix Command: who

Command Library

NAME
who - show who is logged on

SYNOPSIS
who [OPTION]... [ FILE | ARG1 ARG2 ]

DESCRIPTION
-a, --all

same as -b -d --login -p -r -t -T -u

-b, --boot

time of last system boot

-d, --dead

print dead processes

-H, --heading

print line of column headings

-i, --idle

add idle time as HOURS:MINUTES, . or old (deprecated, use -u)

--login

print system login processes (equivalent to SUS -l)

-l, --lookup
attempt to canonicalize hostnames via DNS (-l is deprecated, use --lookup)

-m

only hostname and user associated with stdin

-p, --process

print active processes spawned by init

-q, --count

all login names and number of users logged on

-r, --runlevel

print current runlevel

-s, --short

print only name, line, and time (default)

-t, --time

print last system clock change

-T, -w, --mesg

add user's message status as +, - or ?

-u, --users

list users logged in

--message

same as -T

--writable

same as -T

--help

display this help and exit

--version

output version information and exit

If FILE is not specified, use /var/run/utmp. /var/log/wtmp as FILE is common. If ARG1 ARG2 given,
-m presumed: `am i' or `mom likes' are usual.
The whatis Command

The whatis command provides very brief descriptions of command line


programs (i.e., all-text mode programs) and other topics related to Linux and
other Unix-like operating systems.
It accomplishes this by searching the short descriptions in the whatis
database for each keyword provided to it as an argument (i.e., input data).
This database contains just the title, section number and description from the
NAME section of each page in the man manual that is built into most Unix-
like systems.
The syntax for whatis is:
whatis keyword(s)

For example, the following provides a single line summary of the head
command (which by default displays the first ten lines of each file that is
provided to it as an argument):
whatis head

whatis can be used to simultaneously search for information about multiple


topics. For example, the following would provide information about both
head and tail (which by default reads the final ten lines of files):
whatis head tail

The output of whatis is limited by the fact that it provides only a single line
for each keyword found in the database; thus it supplies incomplete
information about even moderately complex commands. For example, the
following use of whatis to obtain information about the cat command
generates the output "concatenate files and print on the standard output":
whatis cat

However, this omits some important information about cat, particularly the
facts that it is very convenient to use for reading files and that it is also used
to create and write to files.
whatis is similar to the apropos command. However, apropos is more
powerful in that its arguments are not limited to complete words but can also
be strings (i.e., any finite sequences of characters) which comprise parts of
words. Both commands are unusual in that they have no options.
The man command (which is used to read the built-in manual pages), when
used with its -f option, produces the same output as whatis. Thus, for
example,
man -f cat

is equivalent to
whatis cat

The whatis database is a plain text (i.e., human-readable characters) file that
is generated automatically by the makewhatis program. Its location varies
according to the particular system; in the case of Red Hat Linux 9, for
example, its full path is /var/cache/man/whatis.
If desired, the database can be viewed using a command such as the
following:
cat /var/cache/man/whatis | less

In this command the output of cat /var/cache/man/whatis is piped (i.e., sent)


to the less command in order to make it easier to read by displaying only a
single page at a time rather than scrolling down the screen at high speed.

About whatis
whatis displays short manual page descriptions.

Syntax
whatis [-dlhvV] [-r|-w] [-s list] [-m system[,...]] [-M path] [-L locale]
[-C file] name ...
Each manual page has a short description available within it. whatis searches the manual page names
and displays the manual page descriptions of any name matched.

name may contain wildcards (-w) or be a regular expression (-r). Using these options, it may be
necessary to quote the name or escape (\) the special characters to stop the shell from interpreting
them.

index databases are used during the search, and are updated by the mandb program. Depending on
your installation, this may be run by a periodic cron job, or may need to be run manually after new
manual pages have been installed. To produce an old style text whatis database from the relative index
database, issue the command:
whatis -M manpath -w '*' | sort > manpath/whatis
where manpath is a manual page hierarchy such as /usr/man.

Options
-d, --debug Print debugging information.

-v, --verbose Print verbose warning messages.

Interpret each name as a regular expression. If a name matches any


part of a page name, a match will be made. This option causes
-r, --regex
whatis to be somewhat slower due to the nature of database
searches.

Interpret each name as a pattern containing shell style wildcards. For


a match to be made, an expanded name must match the entire page
-w, --wildcard
name. This option causes whatis to be somewhat slower due to the
nature of database searches.

-l, --long Do not trim output to the terminal width. Normally, output will be
truncated to the terminal width to avoid ugly results from poorly-
written NAME sections.

Search only the given manual sections. list is a colon- or comma-


separated list of sections. If an entry in list is a simple section, for
-s list, --sections example "3", then the displayed list of descriptions will include pages
list, --section list in sections "3", "3perl", "3x", and so on; while if an entry in list has
an extension, for example "3perl", then the list will only include
pages in that exact part of the manual section.

If this system has access to other operating system's manual page


names, they can be accessed using this option. To search NewOS's
manual page names, use the option "-m NewOS".
-m system[,...],
--systems=syste The system specified can be a combination of comma delimited
m[,...] operating system names. To include a search of the native operating
system's manual page names, include the system name man in the
argument string. This option will override the $SYSTEM environment
variable.

Specify an alternate set of colon-delimited manual page hierarchies


to search. By default, whatis uses the $MANPATH environment
-M path,
variable, unless it is empty or unset, in which case it will determine
--manpath=path
an appropriate manpath based on your $PATH environment variable.
This option overrides the contents of $MANPATH.

whatis will normally determine your current locale by a call to the C


function setlocale which interrogates various environment variables,
possibly including $LC_MESSAGES and $LANG. To temporarily
-L locale,
override the determined value, use this option to supply a locale
--locale=locale
string directly to whatis. Note that it will not take effect until the
search for pages actually begins. Output such as the help message
will always be displayed in the initially determined locale.

-C file, --config- Use this user configuration file rather than the default of
file=file ~/.manpath.

-h, --help Print a help message and exit.

-V, --version Display version information.

Exit Status:
0 Successful program execution.

1 Usage, syntax or configuration file error.

2 Operational error.

1 Nothing was found that matched the criteria


6 specified.
Environment
If $SYSTEM is set, it will have the same effect as if it had been specified as
SYSTEM
the argument to the -m option.

MANPAT If $MANPATH is set, its value is interpreted as the colon-delimited manual


H page hierarchy search path to use.

If $MANWIDTH is set, its value is used as the terminal width (see the --long
MANWID option). If it is not set, the terminal width will be calculated using an ioctl if
TH available, the value of $COLUMNS, or falling back to 80 characters if all else
fails.

Examples
whatis whatis

I. Linux whatis Command


Whatis command is helpful to get brief information about Linux commands or functions. Whatis
command displays man page single line description for command that matches string passed as a
command line argument to whatis command. Whatis command searches for string in its index
databases which is maintained by mandb program. Whatis command picks short description of NAME
section of man page of command that matches to input given to the whatis command.
Whatis provides several command line options to help user in getting brief information of specific
Linux commands as per their need or interest.
Syntax:
$ whatis [-options]
For example, here is the output of whatis command, when it is run without any option.
$ whatis write
write (1) - send a message to another user
write (2) - write to a file descriptor
It displays brief information about write from man pages.

1. Get information from specific sections of man pages using -s option


If we want to get Linux command information from specific section of man pages, then we can
provide sections list using -s or sections or section option. It will restrict whatis command to
display brief information from specified man page section only.
$ whatis -s "1","2" open
open (1) - start a program on a new virtual terminal (VT).
open (2) - open and possibly create a file or device
It displays open command and function brief information from man page sections 1 and 2.
$ whatis -s "2" open
open (2) - open and possibly create a file or device
It displays open function brief information from man page section 2.

2. Search information through wild-cards using -w option


If we want to search Linux commands or functions information using wild card, then whatis command
gives -w or wildcard option. It will make your search specific as per users need.
$ whatis -w 'ab*'
abort (3) - cause abnormal process termination
abs (3) - compute the absolute value of an integer
It displays brief information of Linux commands or functions which start from ab.
$ whatis -w 'ab?'
abs (3) - compute the absolute value of an integer
It displays brief information of Linux commands or functions which start from ab and followed by
any single character.

3. Search information through regular expressions using -r option


If we want to search Linux commands or functions information using regular expressions, then whatis
command gives -r or regex option. It will give flexibility to customize your search for Linux
commands or functions throughout the Linux system.
$ whatis -r '^ab'
abort (3) - cause abnormal process termination
abs (3) - compute the absolute value of an integer
It displays brief information of Linux commands or functions which start from ab.
$ whatis -r 'ab$'
anacrontab (5) - configuration file for anacron
baobab (1) - A graphical tool to analyse disk usage
crontab (1) - maintain crontab files for individual users (Vixie Cron)
crontab (5) - tables for driving cron
fstab (5) - static information about the filesystems
inittab (5) - init daemon configuration
swab (3) - swap adjacent bytes
tc-stab (8) - Generic size table manipulations
It displays brief information of Linux commands or functions which ends with ab.

4. Disable trimmed output using -l option


Generally whatis command trims long output of Linux commands or functions information to avoid
Not good output display on terminal that is going beyond screen. To allow whatis command to show
complete output on screen, -l or long option can be used.
$ whatis ssh-import-id
ssh-import-id (1) - retrieve one or more public keys from a public keyserver
(Launchpad.net by default) and append them to the current user's authorized_keys
file (or some other specifie...
It displays trimmed output of brief information of Linux command.
$ whatis -l ssh-import-id
ssh-import-id (1) - retrieve one or more public keys from a public keyserver
(Launchpad.net by default) and append them to the current user's authorized_keys
file (or some other specified file)
It displays complete output of brief information of Linux command.

5. Restrict search up to specified path using -M option


By default, whatis command uses $MANPATH environment variable. But whatis provides -M or
manpath option to restrict search up to specified path of man pages.
$ whatis -M /usr/share/man hexdump
hexdump (1) - ASCII, decimal, hexadecimal, octal dump
It displays brief information of Linux hexdump command from man pages available at path
/usr/share/man.
$ whatis -M /usr/man hexdump
hexdump: nothing appropriate.
It could not find brief information of Linux hexdump command from specified path /usr/man.

II. Linux whereis Command


Whereis command is helpful to locate binary, source and manual pages of commands in the Linux
system. It is very simple utility and provides several options which are given below with examples.
Syntax:
$ whereis [-options]
For example, whereis command is run without any option.
$ whereis open
open: /bin/open /usr/share/man/man1/open.1.gz /usr/share/man/man2/open.2.gz
It locates binary, source and man pages of open command and here it displayed paths where binary,
man pages of open command is available in the system.

6. Locate binaries using -b option


If we want to locate binary of Linux command, use -b option.
$ whereis -b whereis
whereis: /usr/bin/whereis /usr/bin/X11/whereis
It locates binary of whereis command and displays paths where binary of command is available in
the system.

7. Locate man pages for a command using -m option


If we want to locate man page of Linux command, use -m option.
$ whereis -m whereis
whereis: /usr/share/man/man1/whereis.1.gz
It locates man page of whereis command and displays path where man page of command is
available in the system.

8. Locate source of a command using -s option


If we want to locate source of Linux command, use -s option.
$ whereis -s whereis
whereis:
It locates source of whereis command, but source of whereis command does not exist in the
system, so it did not display path for source of command in the system.

9. Locate unusual entries using -u option


This option is something different that searches for unusual entries. These entries are those command
whose source, binary or man page does not exist in the system as per options [-bms] specified along
with u.
$ whereis -m -u wcgrep
wcgrep:
It checks if specified command (i.e. wcgrep) man page does not exist in the system. Whereis
command with options -m and -u locates for the commands in the system whose man page does not
exist.
$ whereis -m -u grep
$
Here, whereis command with same options is applied on grep command whose man page exists in
the system, so whereis returned nothing and exits normally.

10. Locate binaries in a specified path using -B option


If user wants to search for binary and wants to limit the scope of search for whereis command up to
specified path, then use -B option.
$ whereis -B /bin -f for_loop
for_loop: /bin/for_loop
It locates binary of for_loop user program from path /bin.
$ whereis -B /usr -f open
open: /usr/share/man/man1/open.1.gz /usr/share/man/man2/open.2.gz
If open commands binary is not found at specified path, then it is not shown but whereis command by
default searches for other types (i.e. man page and source) of specified command (i.e. open) and
displays them if found.

11. Locate man pages with limited scope using -M option


If user wants to search for man pages and wants to limit the scope of search for whereis command up
to specified path, then use -M option.
$ whereis -M /usr/share/man/man1 -f open
open: /bin/open /usr/share/man/man1/open.1.gz
$ whereis -M /usr/share/man/man2 -f open
open: /bin/open /usr/share/man/man2/open.2.gz
$ whereis -M /usr/share/man/man3 -f open
open: /bin/open
Here, it is observed that whereis command is displaying man page of open command which is
available in specified path only. But, whereis command by default searches for other types (i.e. binary
and source) of specified command (i.e. open) and displays them if found.

III. Linux which Command


Which command is very small and simple command to locate executables in the system. It allows user
to pass several command names as arguments to get their paths in the system. which commands
searches the path of executable in system paths set in $PATH environment variable.
Syntax:
$ which [-option]
For example,
$ which ls gdb open grep
/bin/ls
/usr/bin/gdb
/bin/open
/bin/grep
It locates command names ls, gdb, open and grep specified as arguments to which
command and displays paths of each executable where it exists in the system.

12. Display all the paths using -a option


which command gives option -a that displays all paths of executable matching to argument.
$ which echo
/usr/sbin/echo
Above will search display the executable echo from all paths set in $PATH environment variable
and displays the first path where echo executable is found. It may be case that executable is placed at
other paths of $PATH environment variable as well. To get all paths where executable is present in the
system, -a option can be used.
$ which -a echo
/usr/sbin/echo
/bin/echo
>

NAME
whatis - search the whatis database for complete words.

SYNOPSIS
whatis keyword ...

DESCRIPTION
whatis searches a set of database files containing short descriptions of system
commands for keywords and displays the result on the standard output. Only complete
word matches are displayed.

The whatis database is created using the command /usr/sbin/makewhatis.

whatis
whatis displays short man page descriptions. Unlike
Examples:
$ whatis info
info (1) - read Info documents
info (5) - readable online documentation
$ whatis chmod
chmod (1) - change file modes
chmod, fchmod (2) - change mode of file

What is whereis ?
Whereis command is used to find out where the binary, source, and man page files for a command is
located.

3 whereis Examples
Find whereis a UNIX command
When you want to find out where a specific Unix command exists (for example, where does ls
command exists?), you can execute the following command.
$ whereis ls
ls: /bin/ls /usr/share/man/man1/ls.1.gz /usr/share/man/man1p/ls.1p.gz

Find whereis a UNIX command executable is located


When you want to know only where the executable for a specific command is available, use -b option.
This is more handy, and you are most likely be using whereis command to find out the location of
only executables.
$ whereis -b ls
ls: /bin/ls

Change the search location of whereis command


When you want to search an executable from a path other than the whereis default path, you can use
-B option and give path as argument to it.
$ whereis -u -B /tmp -f lsmk
lsmk: /tmp/lsmk
This searches for the executable lsmk in the /tmp directory, and displays it, if it is available.

Syntax and Options


Short
Optio Option Description
n

-b Search only for binaries

-m Search only for manual sections

-s Search only for sources

Search for unusual entries. A file is said to be unusual if it does not have one entry
-u of each requested type. Thus whereis -m -u asks for those files in the current
directory which have no documentation

-B Change or otherwise limit the places where whereis searches for binaries

-M Change or otherwise limit the places where whereis searches for manual sections

-S Change or otherwise limit the places where whereis searches for sources

Terminate the last directory list and signals the start of file names, and must be
used when any of the -B, -M, or -S options are used

About whereis
-f Locates the binary, source, and manual page files for a command.

Syntax
whereis [-bmsu] [-BMS directory... -f] filename...

Description
whereis locates source/binary and manuals sections for specified files. The supplied names are
first stripped of leading pathname components and any (single) trailing extension of the form
".ext", for example, ".c". Prefixes of "s." resulting from use of source code control are also
handled. whereis then attempts to locate the desired program in a list of standard Linux places.

Options
-b Search only for binaries.

-
Search only for manual sections.
m

-s Search only for sources.

Search for unusual entries. A file is said to be unusual if it does not have one
-u entry of each requested type. For example, "whereis -m -u *" asks for those
files in the current directory which have no documentation.

-B Change or otherwise limit the places where whereis searches for binaries.

- Change or otherwise limit the places where whereis searches for manual
M sections.

-S Change or otherwise limit the places where whereis searches for sources.

Terminate the last directory list and signals the start of file names, and must be
-f
used when any of the -B, -M, or -S options are used.

Examples
whereis perl
List the directories where the perl source files, documentation, and binaries are stored.
whereis -u -M /usr/man/man1 -S /usr/src -f *
Find all files in the current directory which are not documented in /usr/man/man1, whose
source resides in /usr/src.

am a new Linux and Unix-like system command line user. How do I find and locate the binary,
source, and manual page files for a given command?

You need to use the whereiscommand to find the source, binary, and manuals sections for
specified commands or files.
whereis command
details

Locating command or
Description
program

Category Searching

Difficulty Easy

Root privileges No

Estimated completion 10m


time

Contents

Syntax

Examples

Search only for binaries

Search only for manual sections

Search only for sources

Searches for unusual files

Limit the searches for binaries to specific


directories

Options

See also
A binary is nothing but an executable from of a command such as ls or program
such as Gimp. Use this command to find out:

1. The location of a binary file.

2. The location of source code.

3. The location of man page.

Purpose
Find the binary, source code and man page for specified program or command.

Syntax
The basic syntax is as follows:
whereis command

OR
whereis program

OR
whereis [options] program

OR
whereis -BMS directory -f command

whereis command examples


To find out the location of the executable, source code and man page for the date command,
type:
$ whereis date
Sample outputs:

Animated gif 01: whereis command running on my Debian based server

How do I only search for binary files?


Pass the -b option as follows:
$ whereis -b date

How do I only search for manual sections files?


Pass the -m option as follows:
$ whereis -m date

How do I only search for source code files?


Pass the -s option as follows:
$ whereis -s date

How do I only Search for unusual entries?


A file is said to be unusual if it does not have one entry of each requested type. Thus the
following example, asks for those files in the current directory which have no documentation:
$ whereis -m -u *

How can I limit the searches for binaries to specific directories?


You can pass the following option to limit limit the places where whereis searches for files:
-B /path/to/dir : Limit the places where whereis searches for binaries.

-M /path/to/dir : Limit the places where whereis searches for manual


sections.

-S /path/to/dir : Limit the places where whereis searches for sources.

You must pass the -f option when any of the -B, -M, or -S options are used. The -f option
terminate the last directory list and signals the start of file names. In this example, limit search
for binary files in /bin/ directory only for ls and gcc commands:
$ whereis -B /bin -f ls gcc
Sample outputs:
ls: /bin/ls /usr/share/man/man1/ls.1.gz
gcc:
There is no output for the gcc command since it is located in /usr/bin/ directory. To find all of
the files in the /sbin/ directory that either are not documented in the /usr/man/man8 directory or
do not have source in the /root/src directory, enter:
# cd /sbin
# whereis -u -M /usr/man/man8/ -S /root/src/ -f *

whereis command options


From the whereis(1) command man page:
Optio
Meaning
n

-f Define search scope.

-b Search only binaries.

-B Define binaries lookup path.

-m Search only manual paths.

-M Define man lookup path.

-s Search only sources path.

-S Define sources lookup path.

-u Search from unusual enties.

Output version information


-V
and exit.

-h Display this help and exit.

See also
whereis(1) Linux/Unix command man page

NAME
whereis - locate the binary, source, and manual page files for a command
SYNOPSIS
whereis [ -bmsu ] [ -BMS directory... -f ] filename ...

DESCRIPTION
whereis locates source/binary and manuals sections for specified files. The
supplied names are first stripped of leading pathname components and any
(single) trailing extension of the form .ext, for example, .c. Prefixes of s. resulting
from use of source code control are also dealt with. whereis then attempts to
locate the desired program in a list of standard Linux places.

OPTIONS
-b

Search only for binaries.

-m

Search only for manual sections.

-s

Search only for sources.

-u

Search for unusual entries. A file is said to be unusual if it does not have one
entry of each requested type. Thus `whereis -m -u *' asks for those files
in the current directory which have no documentation.

-B

Change or otherwise limit the places where whereis searches for binaries.

-M

Change or otherwise limit the places where whereis searches for manual
sections.

-S

Change or otherwise limit the places where whereis searches for sources.

-f

Terminate the last directory list and signals the start of file names, and must
be used when any of the -B, -M, or -S options are used.

EXAMPLE
ind all files in /usr/bin which are not documented in /usr/man/man1 with source in /usr/src:
example% cd /usr/bin
example% whereis -u -M /usr/man/man1 -S /usr/src -f *

The whereis command is used to locate the binary, the source code and the online manual page
for any specified program.
A binary is an executable (i.e., ready to run) form of a program. Source code is the original
form of a program as written by a human using a programming language and before it has been
converted by a compiler into a binary. The online manual pages, commonly referred to as man
pages, are normally accessed using the man command.
whereis's basic syntax is
whereis [option(s)] program_name(s)

When used without any options, which is most commonly the case, whereis attempts to supply
the absolute path names (i.e., the path to the root directory) for the binary, source code and man
page for every program name (including command names, which are generally the same as
program names) that is supplied to it as an argument (i.e., input). Any number of names can be
accepted as arguments, and the results for each will be returned on a separate line.
Thus, for example, the following would be used to attempt to find the locations of the
executable, source code and man page for the ls command (which is used to list the contents of
any specified directory):
whereis ls

Although whereis ideally returns three pieces of information for each argument, in reality it
often returns fewer and sometimes returns more. For example, it will not return a location for
source code for a program on a computer for which the source code has not been installed
(which is common when programs are installed in precompiled form during installation of the
operating system). Likewise, there may be no man pages for some commands, or there may be
more than one.
For some commands it might be the case that no executable is returned. Examples include alias
and umask. This is presumably because no separate executables with these names exist and
such commands are built directly into the shell (i.e., the program that executes commands
typed in by a user and displays their results).
If an executable, source code or man page file exists on a computer but has not installed in a
standard location, no result will be returned for it. This is because whereis only searches in
such locations. An example is the situation in which a user has installed a program in its home
directory (i.e., the directory which contains configuration files, programs and data specific to
that user) rather than in directories that are accessible to all users.
In the event that nothing is found for one or more of the three types of information for which
whereis searches for each argument, no error message or other notification is provided. If
multiple results are found, whereis returns all of them.
In some situations, whereis might return only a single entry for some commands. This is true in
the case of the spell command (which, as its name implies, is used to check the spelling of text
files), at least on some systems, as can be seen by running the following:
whereis spell

Several options are available to limit the type of results returned by whereis (as is the case with
the wc command, which by default counts the number of lines, words and characters that are
contained in text). The -b option tells it to search only for binaries. The -m option tells it to
search only for man pages. The -s option tells it to search only for sources. Thus, for example,
the following could be used to search for only the binaries and source code for the whoami
command (which reports the owner of the current login session):
whereis -b whoami

As is generally (but not always) the case with single-letter options for shell programs, these
options can be used together in any combination and any order. The order in which the results
are displayed is not affected by the order in which the options are used.

Linux / Unix Command: which

Command Library

NAME
which - shows the full path of (shell) commands.

SYNOPSIS
which [options] [--] programname [...]

DESCRIPTION
Which takes one or more arguments. For each of its arguments it prints to stdout
the full path of the executables that would have been executed when this
argument had been entered at the shell prompt. It does this by searching for an
executable or script in the directories listed in the environment variable PATH
using the same algorithm as bash(1).

This man page is generated from the file which.texinfo.

OPTIONS
--all, -a

Print all matching executables in PATH, not just the first.

--read-alias, -i

Read aliases from stdin, reporting matching ones on stdout. This is useful in
combination with using an alias for which itself. For example
alias which='alias | which -i'.
--skip-alias

Ignore option `--read-alias', if any. This is useful to explicity search for


normal binaries, while using the `--read-alias' option in an alias or function
for which.

--read-functions

Read shell function definitions from stdin, reporting matching ones on


stdout. This is useful in combination with using a shell function for which
itself. For example:
which() { declare -f | which --read-functions $@ }
export -f which

--skip-functions

Ignore option `--read-functions', if any. This is useful to explicity search for


normal binaries, while using the `--read-functions' option in an alias or
function for which.

--skip-dot

Skip directories in PATH that start with a dot.

--skip-tilde

Skip directories in PATH that start with a tilde and executables which reside
in the HOME directory.

--show-dot

If a directory in PATH starts with a dot and a matching executable was


found for that path, then print "./programname" rather than the full path.

--show-tilde

Output a tilde when a directory matches the HOME directory. This option is
ignored when which is invoked as root.

--tty-only

Stop processing options on the right if not on tty.

--version,-v,-V

Print version information on standard output then exit successfully.

--help

Print usage information on standard output then exit successfully.

RETURN VALUE
Which returns the number of failed arguments, or -1 when no `programname' was
given.

EXAMPLE
The recommended way to use this utility is by adding an alias (C shell) or shell
function (Bourne shell) for which like the following:

[ba]sh:
which ()
{
(alias; declare -f) | /usr/bin/which --tty-only --read-alias --read-
functions --show-tilde --show-dot $@
}
export -f which
[t]csh:
alias which 'alias | /usr/bin/which --tty-only --read-alias --show-dot
--show-tilde'
This will print the readable ~/ and ./ when starting which from your prompt, while still printing
the full path when used from a script:
> which q2
~/bin/q2
> echo `which q2`
/home/carlo/bin/q2

12 Linux Which Command, Whatis Command,


Whereis Command Examples
by Himanshu Arora on April 23, 2013
This Linux tutorial will explain the three W commands. The three Ws are whatis, whereis
and which commands.

You already know how to use find command to efficiently fo find a file.
Now, these three W commands will help you to locate more stuff from Linux command line.

I. Linux whatis Command


Whatis command is helpful to get brief information about Linux commands or functions.
Whatis command displays man page single line description for command that matches string
passed as a command line argument to whatis command. Whatis command searches for string
in its index databases which is maintained by mandb program. Whatis command picks short
description of NAME section of man page of command that matches to input given to the
whatis command.
Whatis provides several command line options to help user in getting brief information of
specific Linux commands as per their need or interest.
Syntax:
$ whatis [-options]
For example, here is the output of whatis command, when it is run without any option.
$ whatis write
write (1) - send a message to another user
write (2) - write to a file descriptor
It displays brief information about write from man pages.

About which
Locate the executable file associated with a given command.

Syntax
which -a [filename] ...

Description
which returns the pathnames of the files (or links) which would be executed in the current
environment, had the filename (or filenames) been given as a command (or commands) in a
strictly POSIX-conformant shell. It does this by searching the paths in the PATH environment
variable for executable files matching the names of the arguments.

which does not follow symbolic links.

Options
- Print all matching pathnames of each
a matching filename.

Exit Status
which returns the following value, depending on what occurred:
0 All filenames were found, and all were executable.

One or more filenames were not found, or were not


1
executable.

2 An invalid option was specified.

Examples
which sh
Locates the pathname of the file which would be run if the sh command were executed. On
most systems, this will output:
/bin/sh

xman - Manual page display program for the X Window System

Synopsis
xman [ -options ... ]

Description
Xman is a manual page browser. The default size of the initial xman window is
small so that you can leave it running throughout your entire login session. In the
initial window there are three options: Help will pop up a window with on-line help,
Quit will exit, and Manual Page will pop up a window with a manual page browser
in it. Typing Control-S will pop up a window prompting for a specific manual page
to display. You may display more than one manual page browser window at a time
from a single execution of xman.

For further information on using xman, please read the on-line help information. Most of this
manual will discuss customization of xman.

Options
Xman supports all standard Toolkit command line arguments (see X(1) ). The following
additional arguments are supported.
-helpfile filename

Specifies a helpfile to use other than the default.

-bothshown

Allows both the manual page and manual directory to be on the screen at
the same time.

-notopbox

Starts without the Top Menu with the three buttons in it.

-geometry WxH+X+Y

Sets the size and location of the Top Menu with the three buttons in it.

-pagesize WxH+X+Y

Sets the size and location of all the Manual Pages.

Customizing Xman
Xman allows customization of both the directories to be searched for manual pages, and the
name that each directory will map to in the Sections menu. Xman determines which directories
it will search by reading the MANPATH environment variable. If no MANPATH is found then
the directory is /usr/man is searched on POSIX systems. This environment is expected to be a
colon-separated list of directories for xman to search.

setenv MANPATH /mit/kit/man:/usr/man


By default, xman will search each of the following directories (in each of the directories
specified in the users MANPATH) for manual pages. If manual pages exist in that directory
then they are added to list of manual pages for the corresponding menu item. A menu item is
only displayed for those sections that actually contain manual pages.
Directory Section Name
--------- ------------
man1 (1) User Commands
man2 (2) System Calls
man3 (3) Subroutines
man4 (4) Devices
man5 (5) File Formats
man6 (6) Games
man7 (7) Miscellaneous
man8 (8) Sys. Administration
manl (l) Local
mann (n) New
mano (o) Old
For instance, a user has three directories in her manual path and each contain a
directory called man3. All these manual pages will appear alphabetically sorted
when the user selects the menu item called (3) Subroutines. If there is no directory
called mano in any of the directories in her MANPATH, or there are no manual
pages in any of the directories called mano then no menu item will be displayed
for the section called (o) Old.

Bsd and Linux Systems


In newer BSD and Linux systems, Xman will search for a file named /etc/man.conf which will
contain the list of directories containing manual pages. See man.conf(5) for a complete
description of the file format.

the Mandesc File


By using the mandesc file a user or system manager is able to more closely control which
manual pages will appear in each of the sections represented by menu items in the Sections
menu. This functionality is only available on a section by section basis, and individual manual
pages may not be handled in this manner. (Although generous use of symbolic links -- see ln(1)
-- will allow almost any configuration you can imagine.)
The format of the mandesc file is a character followed by a label. The character determines
which of the sections will be added under this label. For instance suppose that you would like
to create an extra menu item that contains all programmer subroutines. This label should
contain all manual pages in both sections two and three. The mandesc file would look like this:

2Programmer Subroutines
3Programmer Subroutines
This will add a menu item to the Sections menu that would bring up a listing of all
manual pages in sections two and three of the Programmers Manual. Since the
label names are exactly the same they will be added to the same section. Note,
however, that the original sections still exist.

If you want to completely ignore the default sections in a manual directory then add the line:
no default sections
anywhere in your mandesc file. This keeps xman from searching the default
manual sections In that directory only. As an example, suppose you want to do the
same thing as above, but you don't think that it is useful to have the System Calls
or Subroutines sections any longer. You would need to duplicate the default
entries, as well as adding your new one.

no default sections
1(1) User Commands
2Programmer Subroutines
3Programmer Subroutines
4(4) Devices
5(5) File Formats
6(6) Games
7(7) Miscellaneous
8(8) Sys. Administration
l(l) Local
n(n) New
o(o) Old
Xman will read any section that is of the from man<character>, where
<character> is an upper or lower case letter (they are treated distinctly) or a
numeral (0-9). Be warned, however, that man(1) and catman(8) will not search
directories that are non-standard.

Widgets
In order to specify resources, it is useful to know the hierarchy of the widgets
which compose xman. In the notation below, indentation indicates hierarchical
structure. The widget class name is given first, followed by the widget instance
name.

Xman xman (This widget is never used)


TopLevelShell topBox
Form form
Label topLabel
Command helpButton
Command quitButton
Command manpageButton
TransientShell search
DialogWidgetClass dialog
Label label
Text value
Command manualPage
Command apropos
Command cancel
TransientShell pleaseStandBy
Label label
TopLevelShell manualBrowser
Paned Manpage_Vpane
Paned horizPane
MenuButton options
MenuButton sections
Label manualBrowser
Viewport directory
List directory
List directory
.
. (one for each section,
. created on the fly)
.
ScrollByLine manualPage
SimpleMenu optionMenu
SmeBSB displayDirectory
SmeBSB displayManualPage
SmeBSB help
SmeBSB search
SmeBSB showBothScreens
SmeBSB removeThisManpage
SmeBSB openNewManpage
SmeBSB showVersion
SmeBSB quit
SimpleMenu sectionMenu
SmeBSB <name of section>
.
. (one for each section)
.
TransientShell search
DialogWidgetClass dialog
Label label
Text value
Command manualPage
Command apropos
Command cancel
TransientShell pleaseStandBy
Label label
TransientShell likeToSave
Dialog dialog
Label label
Text value
Command yes
Command no
TopLevelShell help
Paned Manpage_Vpane
Paned horizPane
MenuButton options
MenuButton sections
Label manualBrowser
ScrollByLine manualPage
SimpleMenu optionMenu
SmeBSB displayDirectory
SmeBSB displayManualPage
SmeBSB help
SmeBSB search
SmeBSB showBothScreens
SmeBSB removeThisManpage
SmeBSB openNewManpage
SmeBSB showVersion
SmeBSB quit

Application Resources
xman has the following application-specific resources which allow customizations
unique to xman.

manualFontNormal (Class Font)

The font to use for normal text in the manual pages.

manualFontBold (Class Font)

The font to use for bold text in the manual pages.

manualFontItalic (Class Font)

The font to use for italic text in the manual pages.

directoryFontNormal (Class Font)

The font to use for the directory text.

bothShown (Class Boolean)

Either `true' or `false,' specifies whether or not you want both the directory
and the manual page shown at start up.

directoryHeight (Class DirectoryHeight)

The height in pixels of the directory, when the directory and the manual
page are shown simultaneously.

topCursor (Class Cursor)

The cursor to use in the top box.

helpCursor (Class Cursor)

The cursor to use in the help window.

manpageCursor (Class Cursor)

The cursor to use in the manual page window.

searchEntryCursor (Class Cursor)

The cursor to use in the search entry text widget.

pointerColor (Class Foreground)

This is the color of all the cursors (pointers) specified above. The name was
chosen to be compatible with xterm.

helpFile (Class File)

Use this rather than the system default helpfile.

topBox (Class Boolean)

Either `true' or `false,' determines whether the top box (containing the help,
quit and manual page buttons) or a manual page is put on the screen at
start-up. The default is true.

verticalList (Class Boolean)

Either `true' or `false,' determines whether the directory listing is vertically


or horizontally organized. The default is horizontal (false).

Global Actions
Xman defines all user interaction through global actions. This allows the user to
modify the translation table of any widget, and bind any event to the new user
action. The list of actions supported by xman are:

GotoPage(page)

When used in a manual page display window this will allow the user to move
between a directory and manual page display. The page argument can be
either Directory or ManualPage.
Quit()

This action may be used anywhere, and will exit xman.

Search(type, action)

Only useful when used in a search popup, this action will cause the search
widget to perform the named search type on the string in the search
popup's value widget. This action will also pop down the search widget. The
type argument can be either Apropos, Manpage or Cancel. If an action of
Open is specified then xman will open a new manual page to display the
results of the search, otherwise xman will attempt to display the results in
the parent of the search popup.

PopupHelp()

This action may be used anywhere, and will popup the help widget.

PopupSearch()

This action may be used anywhere except in a help window. It will cause the
search popup to become active and visible on the screen, allowing the user
search for a manual page.

CreateNewManpage()

This action may be used anywhere, and will create a new manual page
display window.

RemoveThisManpage()

This action may be used in any manual page or help display window. When
called it will remove the window, and clean up all resources associated with
it.

SaveFormattedPage(action)

This action can only be used in the likeToSave popup widget, and tells
xman whether to Save or Cancel a save of the manual page that has just
been formatted.

ShowVersion()

This action may be called from any manual page or help display window,
and will cause the informational display line to show the current version of
xman.

Files
<manpath directory>/man<character>

<manpath directory>/cat<character>

<manpath directory>/mandesc
/usr/share/X11/app-defaults/Xman

specifies required resources.

/tmp

Xman creates temporary files in /tmp for all unformatted man pages and all
apropos searches.

Xman

Contents

1. Introduction

2. Running xman

3. Searching xman

4. Launchers

Discussion thread for this wiki can be found here

Introduction
The original documentation for all Linux systems was a set of files collectively known as the
"man pages" that formed a readily available manual describing the actions and options for each
command. The command "man" followed by an optional section number and the name of the
command for which information was desired brings up the "man page" for that command,
allowing you to learn more about it.
Unfortunately in today's world, many of the man pages are so full of jargon that they seem
incomprehensible to newcomers -- and even, at times, to long-time users of Linux. Still they
are quite useful, especially for refreshing one's memory about details of a command not often
used.
There's one major drawback, however: When you need to find a man page while at the
command line, you must either open a second terminal window to issue the "man" command,
or abort the action under way so that you can run "man" in the current window.
If, like many of us, you are using a terminal window from within your file manager (Nautilus,
Dolphin, Thunar, etc.) or from a desktop launcher, there's an easy option. The purpose of this
post is to show you how to use it, and how to install and configure a launcher that will make it
even simpler to use.
This easy option is a program called "xman" that's installed by default with the X Window
System. It does the same thing as the command "man" does from a terminal, but does so within
its own window on the desktop, and includes a number of features to simplify its use. Since
xman dates from the earliest days of the X system, it doesn't have all the eye candy of more
recent desktop tools, and many of its actions are not at all intuitive, but despite this it's still one
of the tools that I use daily. You may find it equally useful.

Running xman
To get started with xman, open a terminal window and type
xman
followed by the Enter key. You'll see this window appear in your display

This is the "top box" and simply guides you to the next step. Click the
"Manual Page" button, and you'll get the default instruction screen:

You might also like