Sei sulla pagina 1di 50

LINUX UTILITIES

Linux Utilities

1.1. File Handling Utilities


LINUX provides several utilities for working with text files. These utilities can be combined
with each other to provide more complex general purpose tools.

1. cat : Displaying And Creating Files


cat linux command concatenates files and print it on the standard output.
SYNTAX: The Syntax is
cat [OPTIONS] [FILE]...
OPTIONS:
-A

Show all.

-b

Omits line numbers for blank space in the output.

-e

A $ character will be printed at the end of each line prior to a new


line.

-E

Displays a $ (dollar sign) at the end of each line.

-n

Line numbers for all the output lines.

-s

If the output has multiple empty lines it replaces it with one empty
line.

-T

Displays the tab characters in the output.

-v

Non-printing characters (with the exception of tabs, new-lines and


form-feeds) are printed visibly.

EXAMPLE
1. To Create a new file:
cat > file1.txt
This command creates a new file file1.txt.After typing into the file press control+d (^d)
simultaneously to end the file.
2. To Append data into the file:
cat >> file1.txt

U.HARITHA

LINUX UTILITIES
To append data into the same file use append operator >> to write into the file, else the
file will be overwritten (i.e., all of its contents will be erased).
3. To display a file:
cat file1.txt
This command displays the data in the file.
4. To concatenate several files and display:
cat file1.txt file2.txt
The above cat command will concatenate the two files (file1.txt and file2.txt) and it will
display the output in the screen. Sometimes the output may not fit the monitor screen. In such
situation you can print those files in a new file or display the file using less command.
cat file1.txt file2.txt | less
5. To concatenate several files and to transfer the output to another file.
cat file1.txt file2.txt > file3.txt
In the above example the output is redirected to new file file3.txt. The cat command will
create new file file3.txt and store the concatenated output into file3.txt.

2. rm: Deleting Files


rm linux command is used to remove/delete the file from the directory.
SYNTAX: The syntax is
rm [options] [file|directory]
OPTIONS
-f

Remove all files in a directory without prompting the user.

-i

Interactive. With this option, rm prompts for confirmation before


removing any files.

-r (or) -R

Recursively remove directories and subdirectories in the argument


list. The directory will be emptied of files and removed. The user is
normally prompted for removal of any write-protected files which the
directory contains.

EXAMPLE:
1. To Remove / Delete a file:
rm file1.txt
Here rm command will remove/delete the file file1.txt.

U.HARITHA

LINUX UTILITIES
2. To delete a directory tree:
rm -ir tmp
This rm command recursively removes the contents of all subdirectories of the tmp
directory, prompting you regarding the removal of each file, and then removes the tmp
directory itself.
3. To remove more files at once
rm file1.txt file2.txt
rm command removes file1.txt and file2.txt files at the same time.

3. cp :Copying A File
cp command copy files from one location to another. If the destination is an existing file,
then the file is overwritten; if the destination is an existing directory, the file is copied into the
directory (the directory is not overwritten).
SYNTAX: The Syntax is
cp [OPTIONS]... SOURCE DEST
cp [OPTIONS]... SOURCE... DIRECTORY
cp [OPTIONS]... --target-directory=DIRECTORY SOURCE...

OPTIONS:

-a

same as -dpR.

--backup[=CONTROL]

make a backup of each existing destination file

-b

like --backup but does not accept an argument.

-f

if an existing destination file cannot be opened,


remove it and try again

-p

same

as

--preserve=mode,

ownership,

timestamps.
--preserve[=ATTR_LIST]

preserve the specified attributes (default: mode,


ownership, timestamps) and security contexts, if
possible additional attributes: links, all.

--no-preserve=ATTR_LIST

don't preserve the specified attribute.

--parents

append source path to DIRECTORY.

U.HARITHA

LINUX UTILITIES
EXAMPLE:
1. Copy two files:
cp file1 file2
The above cp command copies the content of file1.php to file2.php.
2. To backup the copied file:
cp -b file1.php file2.php
Backup of file1.php will be created with '~' symbol as file2.php~.
3. Copy folder and subfolders:
cp -R scripts scripts1
The above cp command copy the folder and subfolders from scripts to scripts1.

4. mv: Renaming Files


mv command which is short for move. It is used to move/rename file from
one directory to another. mv command is different from cp command as it completely
removes the file from the source and moves to the directory specified, where cp command
just copies the content from one file to another.
SYNTAX: The Syntax is
mv [-f] [-i] oldname newname
OPTIONS:
-f

This will not prompt before overwriting (equivalent to -reply=yes). mv -f will move the file(s) without prompting even if
it is writing over an existing target.

-i

Prompts before overwriting another file.

EXAMPLE:

1. To Rename / Move a file:


mv file1.txt file2.txt
This command renames file1.txt as file2.txt
2.

To move a directory
mv hscripts tmp

U.HARITHA

LINUX UTILITIES
In the above line mv command moves all the files, directories and sub-directories
from hscripts folder/directory to tmp directory if the tmp directory already exists. If there is
no tmp directory it rename's the hscripts directory as tmp directory.
3. To Move multiple files/More files into another directory
mv file1.txt tmp/file2.txt newdir
This command moves the files file1.txt from the current directory and file2.txt from the tmp
folder/directory to newdir.

5. ls : Listing Files
ls command lists the files and directories under current working directory.
SYNTAX: The Syntax is
ls [OPTIONS]... [FILE]
OPTIONS:

-l

Lists all the files, directories and their mode, Number of links, owner of the
file, file size, Modified date and time and filename.

-t

Lists in order of last modification time.

-a

Lists all entries including hidden files.

-d

Lists directory files instead of contents.

-p

Puts slash at the end of each directories.

-u

List in order of last access time.

-i

Display inode information.

-ltr

List files order by date.

-lSr

List files order by file size

EXAMPLE:
1. Display root directory contents:

ls /
lists the contents of root directory.
2.

Display hidden files and directories:


ls -a
lists all entries including hidden files and directories.

U.HARITHA

LINUX UTILITIES
3. Display inode information:

ls -i
7373073 book.gif
7373074 clock.gif
7373082 globe.gif
7373078 pencil.gif
7373080 child.gif
7373081 email.gif
7373076 indigo.gif
The above command displays filename with inode value.

6. cd : Changing Current Directory


cd command is used to change the directory.
SYNTAX: The Syntax is
cd [directory | ~ | ./ | ../ | - ]
OPTIONS:
-L

Use the physical directory structure.

-P

Forces symbolic links.

EXAMPLE:
1. cd linux-command
This command will take you to the sub-directory(linux-command) from its parent directory.
2. cd ..
This will change to the parent-directory from the current working directory/sub-directory.
3. cd ~

This command will move to the user's home directory which is "/home/username".

U.HARITHA

LINUX UTILITIES
7. mkdir :Making Directories
mkdir command is used to create one or more directories.
SYNTAX: The Syntax is
mkdir [options] directories
OPTIONS:
-m

Set the access mode for the new directories.

-p

Create intervening parent directories if they don't exist.

-v

Print help message for each directory created.

EXAMPLE:

1. Create directory:
mkdir test
The above command is used to create the directory 'test'.
2. Create directory and set permissions:
mkdir -m 666 test
The above command is used to create the directory 'test' and set the read and write
permission.
8. rmdir: Removing Directories
rmdir command is used to delete/remove a directory and its subdirectories.
SYNTAX: The Syntax is
rmdir [options..] Directory
OPTIONS:
p

Allow users to remove the directory dirname and its


parent directories which become empty.

EXAMPLES:
1. To delete/remove a directory
rmdir tmp
rmdir command will remove/delete the directory tmp if the directory is empty.
2.

To delete a directory tree:


rm -ir tmp

U.HARITHA

LINUX UTILITIES

This command recursively removes the contents of all subdirectories of the tmp
directory, prompting

1.2. Security By File Permissions


File ownership is an important component of LINUX that provides a secure method for
storing files. Every file in LINUX has the following attributes:

Owner permissions: The owner's permissions determine what actions the owner of
the file can perform on the file.

Group permissions: The group's permissions determine what actions a user, who is a
member of the group that a file belongs to, can perform on the file.

Other (world) permissions: The permissions for others indicate what action all other
users can perform on the file.

The Permission Indicators:


While using ls -l command it displays various information related to file permission as
follows:
$ls -l /home/amrood
-rwxr-xr-- 1 amrood users 1024 Nov 2 00:10 myfile
drwxr-xr--- 1 amrood users 1024 Nov 2 00:10 mydir
Here first column represents different access mode ie. permission associated with a file or
directory.
The permissions are broken into groups of threes, and each position in the group denotes a
specific permission, in this order: read (r), write (w), execute (x):

The first three characters (2-4) represent the permissions for the file's owner. For
example -rwxr-xr-- represents that onwer has read (r), write (w) and execute (x)
permission.

U.HARITHA

LINUX UTILITIES

The second group of three characters (5-7) consists of the permissions for the group to
which the file belongs. For example -rwxr-xr-- represents that group has read (r) and
execute (x) permission but no write permission.

The last group of three characters (8-10) represents the permissions for everyone else.
For example -rwxr-xr-- represents that other world has read (r) only permission.

File Access Modes:


The permissions of a file are the first line of defense in the security of a LINUX system. The
basic building blocks of LINUX permissions are the read, write, and execute permissions,
which are described below:
1. Read:
Grants the capability to read ie. view the contents of the file.
2. Write:
Grants the capability to modify, or remove the content of the file.
3.

Execute:
User with execute permissions can run a file as a program.

Directory Access Modes:


Directory access modes are listed and organized in the same manner as any other file. There
are a few differences that need to be mentioned:
1. Read:
Access to a directory means that the user can read the contents. The user can look at the
filenames inside the directory.
2. Write:
Access means that the user can add or delete files to the contents of the directory.
3. Execute:
Executing a directory doesn't really make a lot of sense so think of this as a traverse
permission.

U.HARITHA

LINUX UTILITIES
A user must have execute access to the bin directory in order to execute ls or cd command.

Changing Permissions:

Chmod operator

Description

Adds the designated permission(s) to a file or directory.

Removes the designated permission(s) from a file or directory.

Sets the designated permission(s).

To change file or directory permissions, you use the chmod (change mode) command. There
are two ways to use chmod: symbolic mode and absolute mode.

Using chmod in Symbolic Mode:


The easiest way for a beginner to modify file or directory permissions is to use the
symbolic mode. With symbolic permissions you can add, delete, or specify the permission set
you want by using the operators in the following table.
Here's an example using testfile. Running ls -1 on testfile shows that the file's
permissions are as follows:
$ls -l testfile
-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
Then each example chmod command from the preceding table is run on testfile, followed by
ls -l so you can see the permission changes:
$chmod o+wx testfile
$ls -l testfile
-rwxrwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod u-x testfile
$ls -l testfile
-rw-rwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod g=r-x testfile

U.HARITHA

10

LINUX UTILITIES
$ls -l testfile
-rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile
Here's how you could combine these commands on a single line:
$chmod o+wx,u-x,g=r-x testfile
$ls -l testfile
-rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile

Using chmod with Absolute Permissions:


The second way to modify permissions with the chmod command is to use a number
to specify each set of permissions for the file.Each permission is assigned a value, as the
following table shows, and the total of each set of permissions provides a number for that set.
Number

Octal Permission Representation

Ref

No permission

---

Execute permission

--x

Write permission

-w-

Execute and write permission: 1 (execute) + 2 (write) = 3

-wx

Read permission

r--

Read and execute permission: 4 (read) + 1 (execute) = 5

r-x

Read and write permission: 4 (read) + 2 (write) = 6

rw-

All permissions: 4 (read) + 2 (write) + 1 (execute) = 7

Rwx

Here's an example using testfile. Running ls -1 on testfile shows that the file's permissions are
as follows:
$ls -l testfile
-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
Then each example chmod command from the preceding table is run on testfile, followed by
ls -l so you can see the permission changes:
$ chmod 755 testfile
$ls -l testfile
-rwxr-xr-x 1 amrood users 1024 Nov 2 00:10 testfile

U.HARITHA

11

LINUX UTILITIES
$chmod 743 testfile
$ls -l testfile
-rwxr---wx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod 043 testfile
$ls -l testfile
----r---wx 1 amrood users 1024 Nov 2 00:10 testfile

Changing Owners and Groups:


While creating an account on LINUX, it assigns a owner ID and a group ID to each
user. All the permissions mentioned above are also assigned based on Owner and Groups.
Two commands are available to change the owner and the group of files:
1. chown: The chown command stands for "change owner" and is used to change the
owner of a file.
2. chgrp: The chgrp command stands for "change group" and is used to change the
group of a file.

Changing Ownership:
The chown command changes the ownership of a file. The basic syntax is as follows:
$ chown user filelist
The value of user can be either the name of a user on the system or the user id (uid) of a user
on the system.
Following example:
$ chown amrood testfile
Changes the owner of the given file to the user amrood.
NOTE: The super user, root, has the unrestricted capability to change the ownership of a any
file but normal users can change only the owner of files they own.

U.HARITHA

12

LINUX UTILITIES
Changing Group Ownership:
The chrgp command changes the group ownership of a file. The basic syntax is as follows:
$ chgrp group filelist
The value of group can be the name of a group on the system or the group ID (GID) of a
group on the system.
Following example:
$ chgrp special testfile
Changes the group of the given file to special group.

SUID and SGID File Permission:


Often when a command is executed, it will have to be executed with special privileges in
order to accomplish its task.
As an example, when you change your password with the passwd command, your new
password is stored in the file /etc/shadow.
As a regular user, you do not have read or write access to this file for security reasons, but
when you change your password, you need to have write permission to this file. This means
that the passwd program has to give you additional permissions so that you can write to the
file /etc/shadow.
Additional permissions are given to programs via a mechanism known as the Set User ID
(SUID) and Set Group ID (SGID) bits.
When you execute a program that has the SUID bit enabled, you inherit the permissions of
that program's owner. Programs that do not have the SUID bit set are run with the
permissions of the user who started the program.
This is true for SGID as well. Normally programs execute with your group permissions, but
instead your group will be changed just for this program to the group owner of the program.

U.HARITHA

13

LINUX UTILITIES
The SUID and SGID bits will appear as the letter "s" if the permission is available. The SUID
"s" bit will be located in the permission bits where the owners execute permission would
normally reside. For example, the command
$ ls -l /usr/bin/passwd
-r-sr-xr-x 1 root bin 19031 Feb 7 13:47 /usr/bin/passwd*

This shows that the SUID bit is set and that the command is owned by the root. A
capital letter S in the execute position instead of a lowercase s indicates that the execute bit is
not set.
If the sticky bit is enabled on the directory, files can only be removed if you are one of the
following users:

The owner of the sticky directory

The owner of the file being removed

The super user, root

To set the SUID and SGID bits for any directory try the following:
$ chmod ug+s dirname
$ ls -l
drwsr-sr-x 2 root root 4096 Jun 19 06:45 dirname

1.3. Process Utilities


1.

ps :Process Status
ps command is used to report the process status. ps is the short name for Process Status.
SYNTAX: The Syntax is
ps [options]

OPTIONS:
-a

List information about all processes most frequently requested: all


those except process group leaders and processes not associated with
a terminal.

U.HARITHA

14

LINUX UTILITIES
-A or e

List information for all processes.

-d

List information about all processes except session leaders.

-e

List information about every process now running.

-f

Generates a full listing.

-j

Print session ID and process group ID.

-l

Generate a long listing.

EXAMPLE:

1. ps
Output:
PID TTY TIME CMD
2540 pts/1 00:00:00 bash
2621 pts/1 00:00:00 ps
In the above example, typing ps alone would list the current running processes.
2.

ps -f

Output:
UID PID PPID C STIME TTY TIME CMD
nirmala 2540 2536 0 15:31 pts/1 00:00:00 bash
nirmala 2639 2540 0 15:51 pts/1 00:00:00 ps -f
Displays full information about currently running processes.

2. kill :Premature Termination of a Process


kill command is used to kill the background process.
SYNTAX: The Syntax is
kill [-s] [-l] %pid
OPTIONS:
-s

Specify the signal to send. The signal may be given as a signal name or number.

-l

Write all values of signal supported by the implementation, if no operand is given.

-pid

Process id or job id.

-9

Force to kill a process.

U.HARITHA

15

LINUX UTILITIES
EXAMPLE:
Step by Step process:

Open a process music player.


xmms
press ctrl+z to stop the process.

To know group id or job id of the background task.


jobs -l

It will list the background jobs with its job id as,


xmms 3956
kmail 3467

To kill a job or process. kill 3956


kill command kills or terminates the background process xmms.

3. nice: Job Execution with Low Priority


Invokes a command with an altered scheduling priority.
SYNTAX:
nice [-increment | -n increment ] command [argument ... ]
OPTIONS:
-increment | -n

increment must be in the range 1-19; if not specified, an

increment

increment of 10 is assumed. An increment greater than 19 is


equivalent to 19.
The super-user may run commands with priority higher than
normal by using a negative increment such as -10. A negative
increment assigned by an unprivileged user is ignored.

command

The name of a command that is to be invoked. If command


names any of the special built-in utilities, the results are
undefined.

argument

Any string to be supplied as an argument when invoking


command.

U.HARITHA

16

LINUX UTILITIES
EXAMPLE:
nice +13 pico myfile.txt - runs the pico command on myfile.txt with an increment of +13.

4. at: One-Time Execution


Schedules a command to be ran at a particular time, such as a print job late at night.
SYNTAX:
at

executes commands at a specified time.

atq

lists the user's pending jobs, unless the user is the superuser; in that case,
everybody's jobs are listed. The format of the output lines (one for each job)
is: Job number, date, hour, job class.

atrm

deletes jobs, identified by their job number.

batch

executes commands when system load levels permit; in other words, when
the load average drops below 1.5, or the value specified in the invocation of
atrun.
at [-c | -k | -s] [-f filename] [-q queuename] [-m] -t time [date] [-l] [-r]

OPTIONS:

-c

C shell. csh(1) is used to execute the at-job.

-k

Korn shell. ksh(1) is used to execute the at-job.

-s

Bourne shell. sh(1) is used to execute the at-job.

-f filename

Specifies the file that contains the command to run.

-m

Sends mail once the command has been run.

-t time

Specifies at what time you want the command to be ran. Format


hh:mm. am / pm indication can also follow the time otherwise a 24hour clock is used. A timezone name of GMT, UCT or ZULU (case
insensitive) can follow to specify that the time is in Coordinated
Universal Time. Other timezones can be specified using the TZ
environment variable. The below quick times can also be entered:
midnight - Indicates the time 12:00 am (00:00).

U.HARITHA

17

LINUX UTILITIES
noon - Indicates the time 12:00 pm.
now - Indicates the current day and time. Invoking at - now will
submit submit an at-job for potentially immediate execution.
date

Specifies the date you wish it to be ran on. Format month, date, year.
The following quick days can also be entered:
today - Indicates the current day.
tomorrow - Indicates the day following the current day.

-l

Lists the commands that have been set to run.

-r

Cancels the command that you have set in the past.

EXAMPLES:
1. at -m 01:35 < atjob = Run the commands listed in the 'atjob' file at 1:35AM, in
addition all output that is generated from job mail to the user running the task. When
this command has been successfully enter you should receive a prompt similar to the
below example.
commands will be executed using /bin/csh job 1072250520.a at Wed Dec 24
00:22:00 2003
2. at -l = This command will list each of the scheduled jobs as seen below.
1072250520.a Wed Dec 24 00:22:00 2003
3. at -r 1072250520.a = Deletes the job just created.
or
atrm 23 = Deletes job 23.
If you wish to create a job that is repeated you could modify the file
that executes the commands with another command that recreates the job or better yet
use the crontab command.

1.4. Disk Utilities


1. df:
Report the amount of disk space being used by file systems.
SYNTAX:
df [OPTION]... [FILE]...

U.HARITHA

18

LINUX UTILITIES
OPTIONS:
-a, --all

include dummy file systems.


scale sizes by SIZE before printing them. E.g., '-BM' prints

-B, --block-size=SIZE

sizes in units of 1,048,576 bytes. See "SIZE Format" below for


more information.

--total

display a grand total.

-h, --human-readable

print sizes in human readable format (e.g., 1K 234M 2G)

-H, --si

same as -h, but use powers of 1000 instead of 1024.

-i, --inodes

list inode information instead of block usage.

-k

like --block-size=1K.

-l, --local

limit listing to local file systems

--no-sync

do not invoke a sync before getting usage info (This is the


default).

-P, --portability

use the POSIX output format.

--sync

invoke a sync before getting usage info.

-t, --type=TYPE

limit listing to file systems of type TYPE.

-T, --print-type

print file system type.

-x, --exclude-type=TYPE

limit listing to file systems not of type TYPE.

-v

(ignored; included for compatibility reasons.)

--help

display a help message and exit.

--version

output version information and exit.

EXAMPLES:
1. df
Display all file systems and their disk usage, as in the following output:
Filesystem 1K-blocks Used Available Use% Mounted on /dev/loop0 18761008
15246876 2554440 86% / none 4 0 4 0% /sys/fs/cgroup udev 493812 4 493808 1%
/dev tmpfs 100672 1364 99308 2% /run none 5120 0 5120 0% /run/lock none
503352 1764 501588 1% /run/shm none 102400 20 102380 1% /run/user /dev/sda3
174766076 164417964 10348112 95% /host

U.HARITHA

19

LINUX UTILITIES
2. df -h
Same as above, but use "human readable" formatting, as in the following example:
Filesystem Size Used Avail Use% Mounted on /dev/loop0 18G 15G 2.5G 86% /
none 4.0K 0 4.0K 0% /sys/fs/cgroup udev 483M 4.0K 483M 1% /dev tmpfs 99M
1.4M 97M 2% /run none 5.0M 0 5.0M 0% /run/lock none 492M 1.8M 490M 1%
/run/shm none 100M 20K 100M 1% /run/user /dev/sda3 167G 157G 9.9G 95% /host

3. df public_html
Display the amount of free space in the public_html directory, as in the following output:
Filesystem 1K-blocks Used Available Use% Mounted on /dev/loop0 18761008
15246924 2554392 86% /

2. du:
du estimates and displays the disk space used by files.
SYNTAX:
du [OPTION]... [FILE]...
du [OPTION]... --files0-from=F
OPTIONS:
-a, --all

write counts for all files, not just directories.

--apparent-size

print apparent sizes, rather than disk usage; although the apparent size is
usually smaller, it may be larger due to holes in ('sparse') files, internal
fragmentation, indirect blocks, and the like.

-B, --block-

scale sizes by SIZE before printing them. For example, '-BM' prints sizes

size=SIZE

in units of 1,048,576 bytes. (See SIZE format below).

-b, --bytes

equivalent to '--apparent-size --block-size=1'

-c, --total

display a grand total.

-H

equivalent to --dereference-args (-D).

-h,--human-

print sizes in human readable format, rounding values and using

readable

abbreviations. For example, "1K", "234M", "2G", etc.

-k

like --block-size=1K.

-l, --count-links

count sizes many times if hard-linked.

-m

like --block-size=1M.

-d, --max-depth=N print the total for a directory (or file, with --all) only if it is N or fewer

U.HARITHA

20

LINUX UTILITIES
levels below the command line argument; --max-depth=0 is the same as -summarize.
show time of the last modification of any file in the directory, or any of its

--time

subdirectories.
--time=WORD

show time as WORD instead of modification time: atime, access, use,


ctime or status.

--time-

show times using style STYLE: full-iso, long-iso, iso, or +FORMAT.

style=STYLE

(FORMAT is interpreted like the format of 'date'.)

--help

display a help message and exit.

--version

output version information and exit.

EXAMPLES:
1. du -s *.txt
Reports the size of each file in the current directory with the extension .txt. Below is an
example of the output:
8 file1.txt 8 file2.txt 10 file3.txt 2 file4.txt 8 file5.txt 8 file6.txt

2. du -shc *.txt
Display the same data, but in a "human-readable" size format, and display a grand total.
8.0K file1.txt 8.0K file2.txt 10.0K file3.txt 2.0K file4.txt 8.0K file5.txt 8.0K file6.txt 44.0K total

3. mount: Mounting File Systems


The mount command mounts a storage device or filesystem, making it accessible
and attaching it to an existing directory structure.
SYNTAX:
mount [-lhV]
mount -a [-fFnrsvw] [-t vfstype] [-O optlist]
mount [-fnrsvw] [-o option[,option]...] device|dir
mount [-fnrsvw] [-t vfstype] [-o options] device|dir

U.HARITHA

21

LINUX UTILITIES
OPTIONS:
-V, --version

Display version information, and exit.

-h, --help

Display a help message, and exit.

-v, --verbose

Operate verbosely.

-a, --all

Mount all filesystems (of the given types) mentioned in fstab.

-F, --fork

(Used in conjunction with -a): fork off a new incarnation of mount


for each device.

-f, --fake

Causes everything to be done except for the actual system call; in


effect, this "fakes" the mounting of the filesystem.

-i, --internal-only Don't call the /sbin/mount.filesystem helper, even if it exists.


-l

Add labels to the mount output.

EXAMPLES:
1. mount -t type devicename destination_directory
Mount the device of devicename devicename, of type type, at filesystem location
destination_directory.
2. mount -t iso9660 -o ro /dev/cdrom /mnt
Mount a CD-ROM in the directory /mnt. iso9660 is the standard file system for CD-ROMs, o ro tells mount to mount it as a read-only filesystem. /mnt must already exist for this
command to be successful.
3. mount
Display all current mounts. Output will appear similar to the following:
/dev/loop0 on / type ext4 (rw,errors=remount-ro) proc on /proc type proc
(rw,noexec,nosuid,nodev) sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)
none on /sys/fs/cgroup type tmpfs (rw) none on /sys/fs/fuse/connections
type fusectl (rw) none on /sys/kernel/debug type debugfs (rw) none on
/sys/kernel/security type securityfs (rw) udev on /dev type devtmpfs
(rw,mode=0755) devpts on /dev/pts type devpts
(rw,noexec,nosuid,gid=5,mode=0620) tmpfs on /run type tmpfs
(rw,noexec,nosuid,size=10%,mode=0755) none on /run/lock type tmpfs
(rw,noexec,nosuid,nodev,size=5242880) none on /run/shm type tmpfs
(rw,nosuid,nodev) none on /run/user type tmpfs
(rw,noexec,nosuid,nodev,size=104857600,mode=0755) /dev/sda3 on /host type
fuseblk
(rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other,blksize=4096)
binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc

U.HARITHA

22

LINUX UTILITIES
(rw,noexec,nosuid,nodev) gvfsd-fuse on /run/user/lightdm/gvfs type
fuse.gvfsd-fuse (rw,nosuid,nodev,user=lightdm)

4. mount -l -t tmpfs
List all current mounts of type tmpfs. Output will resemble the following:
none on /sys/fs/cgroup type tmpfs (rw) tmpfs on /run type tmpfs
(rw,noexec,nosuid,size=10%,mode=0755) none on /run/lock type tmpfs
(rw,noexec,nosuid,nodev,size=5242880) none on /run/shm type tmpfs
(rw,nosuid,nodev) none on /run/user type tmpfs
(rw,noexec,nosuid,nodev,size=104857600,mode=0755)

5. mount -a
Mount all filesystems listed in the filesystem table file /etc/fstab.
mount -o loop disk1.iso /mnt/disk
Mount the ISO Image file disk1.iso as a loop device (see above) at the directory /mnt/disk.
The directory /mnt/disk must already exist for this command to be successful.

4. umount: Unmounting File Systems


The umount command "unmounts" a mounted filesystem, informing the system to
complete any pending read or write operations, and safely detaching it.
SYNTAX:
umount [-hV]
umount -a [-dflnrv] [-t vfstype] [-O options]
umount [-dflnrv] {dir|device}...
OPTIONS:
N

Unmount without writing in /etc/mtab

-r

In case unmounting fails, try to remount read-only

-d

In case the unmounted device was a loop device, also free this loop device
Dont call the /sbin/umount. helper even if it exists. By default /sbin/umount. helper

-i

is called if one exists.


All of the file systems described in /etc/mtab are unmounted. (With umount version

-a

U.HARITHA

2.7 and later: the proc filesystem is not unmounted.)

23

LINUX UTILITIES
EXAMPLES:
1. To unmount all mounts from remote node Node A, enter:
umount -n nodeA
2. To unmount files and directories of a specific type, enter:
umount -t test
This unmounts all files or directories that have a stanza in the /etc/filesystems file that
contains the type=test attribute.

1.5 Networking Commands


The network commands explains various tools which can be useful when networking
with other computers both within the network and across the internet, obtaining more
information about other computers.

1. ping : Checking the Network


The ping command is useful for determining the status of the network and various foreign
hosts, tracking and isolating hardware and software problems, and testing, measuring, and
managing networks.
SYNTAX:
ping -s [-d] [-l] [-L] [-n] [-r] [-R] [-v] [ -i interface_address ] [-I interval] [-t ttl]
host [packetsize] [count]
OPTIONS:
-n Count

Determines the number of echo requests to send. The default is 4 requests.

-w Timeout

Enables you to adjust the timeout (in milliseconds). The default is 4,000 (a 4second timeout).

-l Size

Enables you to adjust the size of the ping packet. The default size is 32 bytes.

-f

Sets the Do Not Fragment bit on the ping packet. By default, the ping packet
allows fragmentation.

/?

U.HARITHA

Provides command Help.

24

LINUX UTILITIES
EXAMPLES:
1. ping google.com
Ping the host google.com to see if it is alive.
2. ping google.com -c 1
Ping the host google.com once and return to the command line as shown below.
PING google.com (204.228.150.3) 56(84) bytes of data.
64 bytes from www.google.com (204.228.150.3): icmp_seq=1 ttl=63 time=0.267 ms
--- google.com ping statistics --1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev =
0.267/0.267/0.267/0.000 ms

2. telnet:
The Telnet Protocol (TELNET) provides a standard method for terminal devices and
terminal-oriented processes to interface.
TELNET is commonly used by terminal emulation programs that allow you to log
into a remote host. However, TELNET can also be used for terminal-to-terminal
communication and interprocess communication. TELNET is also used by other
protocols (for example, FTP) for establishing a protocol control channel.
SYNTAX:
telnet [-8] [-E] [-L] [-c] [-d] [-r] [ -e escape_char ] [ -l user ] [-n file ] [ host [ port ] ]
OPTIONS:

-8
-E
-L
-c

U.HARITHA

Specifies an 8-bit data path. Negotiating the TELNET BINARY option is


attempted for both input and output.
Stops any character from being recognized as an escape character.
Specifies an 8-bit data path on output. This causes the BINARY option to be
negotiated on output.
Disables the reading of the user's telnetrc file.

25

LINUX UTILITIES
-d

Sets the initial value of the debug toggle to TRUE.


Specifies a user interface similar to rlogin . In this mode, the escape character is
set to the tilde (~) character, unless modified by the -e option. The rlogin escape
character is only recognized when it is preceded by a carriage return. In this

-r

mode, the telnet escape character, normally '^]', must still precede a telnet
command. The rlogin escape character can also be followed by '.\r' or '^Z', and,
like rlogin, closes or suspends the connection, respectively. This option is an
uncommitted inter- face and may change in the future.
Sets the initial escape character to escape_char. escape_char may also be a two

-e
escape_char

character sequence consisting of '^' followed by one character. If the second


character is '?', the DEL character is selected. Otherwise, the second character is
converted to a control character and used as the escape character. If the escape
character is the null string (that is, -e ''), it is disabled.
When connecting to a remote system that understands the ENVIRON option,

-l user

then user will be sent to the remote system as the value for the ENVIRON
variable USER.

-n file

Opens tracefile for recording trace information.

EXAMPLES:
1. telnet host.com
The above example would open a telnet session to the domain host.com.

3. ftp:File Transfer Protocol


The ftp command uses the File Transfer Protocol (FTP) to transfer files between the local
host and a remote host or between two remote hosts. Remote execution of the ftp
command is not recommended.
SYNTAX:
ftp [ -d ] [ -D DataConnTimeOut ] [ -g ] [ -i ] [ -n ] [ -v ] [ -f ] [ -K ] [ -k realm] [-q[-C]][
HostName [ Port ] ]

U.HARITHA

26

LINUX UTILITIES
OPTIONS:
-4

Use only IPv4 to contact any host.

-6

Use IPv6 only.

-p

Use passive mode for data transfers. Allows use of ftp in environments where a firewall
prevents connections from the outside world back to the client machine. Requires that
the ftp server support the PASV command. This is the default if invoked as pftp.

-i

Turns off interactive prompting during multiple file transfers.

-e

Disables command editing and history support, if it was compiled into the ftp
executable. Otherwise, does nothing.

-g

Disables file name globbing.

-v

Verbose option forces ftp to show all responses from the remote server, as well as
report on data transfer statistics.

-d

Enables debugging.

EXAMPLES:
1. ftp abc.xyz.edu
This command will attempt to connect to the ftp server at abc.xyz.edu. If it succeeds, it will
ask you to log in using a username and password. Public ftp servers often allow you to log in
using the username "anonymous" and your email address as password. Once you are logged
in you can get a list of the available ftp commands using the help function:
2. ftp> help
This lists the commands that you can use to show the directory contents, transfer files, and
delete files.
3. ftp> ls
This command prints the names of the files and subdirectories in the current directory on the
remote computer.

U.HARITHA

27

LINUX UTILITIES
4. ftp> cd customers
This command changes the current directory to the subdirecotry "customers", if it exists.
5. ftp> cd ..
Changes the current directory to the parent direcotry.
6. ftp> lcd images
Changes the current directory on the local computer to "images", if it exists.
7. ftp> ascii
Changes to "ascii" mode for transferring text files.
8. ftp> binary
Changes to "binary" mode for transferring all files that are not text files.
9. ftp> get image1.jpg
Downloads the file image1.jpg from the remote computer to the local computer. Warning: If
there already is file with the same name it will be overwritten.
10. ftp> put image2.jpg
Uploads the file image2.jpg from the local computer to the remote computer. Warning: If
there already is file with the same name it will be overwritten.
11. ftp> mget *.jpg
With mget you can download multiple images. This command downloads all files that end
with ".jgp".

U.HARITHA

28

LINUX UTILITIES
4. rlogin: Remote Login
Short for remote login, rlogin establishes a remote connection from your terminal to a
remote machine.
SYNTAX:
rlogin [-8] [-E] [-L] [-ec] [ -l username ] hostname
OPTIONS:
-8

Pass eight-bit data across the net instead of seven-bit data.

-E

Stop any character from being recognized as an escape character.

-L

Allow the rlogin session to be run in "litout" mode.

-ec

Specify a different escape character, c, for the line used to disconnect from the
remote host.

-l username

Specify a different username for the remote login. If you do not use this option,
the remote username used is the same as your local username.

hostname

The remote machine on which rlogin establishes the remote login session.

EXAMPLES:
1. To log in to a remote host with your local user name, enter:
rlogin host2
You are prompted to enter your password and then are logged in to the remote host host2.
To logoff the remote host, and close the connection, enter ~. (tilde, period).
2. To log in to a remote host with a different user name, enter:
rlogin host2 -l dale
You are prompted to enter your password and then are logged in to the remote host host2
with the user name dale.
To logoff the remote host, and close the connection, enter ~. (tilde, period).
3. To log in to a remote host with your local user name and change the escape character,
enter:
rlogin host2 -e\

U.HARITHA

29

LINUX UTILITIES
You are prompted to enter your password and then are logged in to the remote host host2.
The escape character has been changed to \ (backslash).
To logoff the remote host, and close the connection, enter \. (backslash, period).

4. finger :
finger looks up and displays information about system users.
SYNTAX:
{ finger | f }[[ -b][ -h] [ -l][ -p]]|[ -i][ -q][ -s][ -w]][ -f][ -m][ User| User @Host| @Host]
OPTIONS:
-b
-f

Gives a brief, long-form listing.


Suppresses printing of header line on output (the first line that defines the fields that are
being displayed).

-h

Suppresses printing of .project files on long and brief long formats.

-i

Gives a quick listing with idle times.

-l

Gives a long-form listing.

-m

Assumes that the User parameter specifies a user ID (used for discretionary access
control), not a user login name.

-p

Suppresses printing of .plan files on long-form and brief long-form formats.

-q

Gives a quick listing.

-s

Gives a short format list.

-w

Gives a narrow, short-format list.

EXAMPLES:
1. To get information about all users logged in to host alcatraz, enter:
finger @alcatraz
Information similar to the following is displayed:
[alcatraz.austin.ibm.com]
Login

Name

brown

Bob Brown

smith
jones

TTY Idle

When

console

2d

Mar 15 13:19

Susan Smith

pts0

11:

Mar 15 13:01

Joe Jones

tty0

Mar 15 13:01

U.HARITHA

Site Info

30

LINUX UTILITIES
User brown is logged in at the console, user smith is logged in from pseudo teletype
line pts0, and user jones is logged in from tty0.
2.

To get information about user brown at alcatraz, enter:

finger brown@alcatraz
Information similar to the following is displayed:
Login name: brown
Directory: /home/brown

Shell: /home/bin/xinit -L -n Startup

On since May 8 07:13:49 on console


No Plan.
3.

To get information about user brown at a local host in short form, enter:

finger -q brown
Information similar to the following is displayed:
Login

TTY

When

brown

pts/6

Mon Dec1710:5

1.6 Filters
A filter is a command or program which gets its input from standard input, sends its
output to standard output, and may be used anywhere in a pipeline
Standard input or file

filter

standard output

Simple Filters: head, tail, sort, cut, uniq, comm, cmp, diff, tr
Filters with regular expressions: grep, awk, sed
1. head : head makes it easy to output the first part of files.
SYNTAX
head [OPTION]... [FILE]...
DESCRIPTION

U.HARITHA

31

LINUX UTILITIES
head, by default, prints the first 10 lines of each FILE to standard output. With more
than one FILE, it precedes each set of output with a header identifying the file name. If no
FILE is specified, or when FILE is specified as a dash ("-"), head reads from standard input.
OPTIONS

-c, --bytes=[-]num

-n, --lines=[-]num

print the first num bytes of each file; with a leading '-', print
all but the last num bytes of each file.
print the first num lines instead of the first 10; with the
leading '-', print all but the last num lines of each file.

-q, --quiet, --silent

never print headers identifying file names.

-v, --verbose

always print headers identifying file names.

--help

display a help message and exit.

--version

output version information and exit.

EXAMPLES
head -15 myfile.txt
Display the first fifteen lines of myfile.txt.
2. tail - Delivers the last part of the file.
SYNTAX:
tail [+ number] [-l] [-b] [-c] [-r] [-f] [-c number | -n number] [file]
OPTIONS:
+number

This option is only recognized if it is specified first. COUNT is a decimal number

-number

optionally followed by a size letter (`b', `k', `m') as in `-c', or `l' to mean count by
lines, or other option letters (`cfqv').

-l

Units of lines.

-b

Units of blocks.

U.HARITHA

32

LINUX UTILITIES
-c

Units of bytes.

-r

Reverse. Copies lines from the specified starting point in the file in reverse order.
The default for r is to print the entire file in reverse order.

-f

Follow. If the input-file is not a pipe, the program will not terminate after the line of
the input-file has been copied, but will enter an endless loop, wherein it sleeps for a
second and then attempts to read and copy further records from the input-file. Thus
it may be used to monitor the growth of a file that is being written by some other
process.

-c number

The number option-argument must be a decimal integer whose sign affects the
location in the file, measured in bytes, to begin the copying:
+

Copying starts relative to the beginning of the file.

Copying starts relative to the end of the file.

None

Copying starts relative to the end of the file.

The origin for counting is 1; that is, -c+1 represents the first byte of the file, -c-1 the
last.
-n number

Equivalent to -c number, except the starting location in the file is measured in lines
instead of bytes. The origin for counting is 1; that is, -n+1 represents the first line of
the file, -n-1 the last.

File

Name of the file you wish to display

EXAMPLES
1. tail myfile.txt
The above example would list the last 10 (default) lines of the file myfile.txt.
2. tail myfile.txt -n 100
The above example would list the last 100 lines in the file myfile.txt.
3. tail -f myfile.txt
This next example displays the last 10 lines and then updates the file as new lines are being
added. This is a great command to use to watch log files or logs in real-time.

U.HARITHA

33

LINUX UTILITIES
4.

tail -f access.log | grep 24.10.160.10

Finally, if you're trying to view a file such as the Apache access log file that is updated
frequently you can pipe its output through the grep command to filter out only the content
you want. In this above example, we're watching the access.log for any IP address of
24.10.160.10
3. Sort - Sorts the lines in a text file.
SYNTAX
sort [options]... [file]
OPTIONS:
-b

Ignores spaces at beginning of the line.

-c

Check whether input is sorted; do not sort

-d

Uses dictionary sort order and ignores the punctuation.

-f

Ignores caps

-g

Compare according to general numerical value

-i

Ignores nonprinting control characters.

-m

Merges two or more input files into one sorted output.

-M

Treats the first three letters in the line as a month (such as may.)

-n

Sorts by the beginning of the number at the beginning of the line.

-o

Write result to FILE instead of standard output

-r

Sorts in reverse order

-s

Stabilize sort by disabling last-resort comparison

-u

If line is duplicated only display once

-z

End lines with 0 byte, not newline

+fields
filename
-o outputfile

U.HARITHA

Sorts by fields , usually by tabs


The name of the file that needs to be sorted.
Sends the sorted output to a file.

34

LINUX UTILITIES
EXAMPLES
sort -r file.txt
Sort the file, file.txt in reverse order.
4. cut - Remove or "cut out" sections of each line of a file or files.
SYNTAX:
cut OPTION... [FILE]...
OPTIONS:
-b, --bytes=LIST

Select only the bytes specified in LIST.

-c, --characters=LIST

Select only the characters specified in LIST

-d, --delimiter=DELIM

use DELIM instead of a tab for the field delimiter

-f, --fields=LIST
-n
--complement
-s, --only-delimited
--outputdelimiter=STRING
--help
--version

select only these fields; also print any line that contains no delimiter
character, unless the -s option is specified
This option is ignored, but is included for compatibility reasons.
complement the set of selected bytes, characters or fields.
do not print lines not containing delimiters.
use STRING as the output delimiter string. The default is to use the
input delimiter.
Display a help message and exit.
output version information and exit.

EXAMPLES
1. cut -c3 file.txt
Outputs the third character of every line of the file file.txt, cutting out the others.
2. cut -c1-3 file.txt
Outputs the first three characters of every line of the file file.txt, cutting out the rest.
3. cut -c3- file.txt

U.HARITHA

35

LINUX UTILITIES
Outputs the third through the last characters of each line of the file file.txt, cutting out the firs
two characters.
4. cut -c- file.txt
Outputs all of every line of the file file.txt, cutting out nothing.
5. cut -d':' -f1 /etc/passwd
Outputs the first field of the file /etc/passwd, where fields are delimited by a colon (':'). The
first field of /etc/passwd is the username, so this command will output every username in the
passwd file.
5. uniq : Report or filter out repeated lines in a file.
SYNTAX
uniq [-c | -d | -u ] [ -f fields ] [ -s char ] [-n] [+m] [input_file [ output_file ] ]
OPTIONS
-c

Precede each output line with a count of the number of times the line occurred in the
input.

-d

Suppress the writing of lines that are not repeated in the input.

-u

Suppress the writing of lines that are repeated in the input.

-f fields

Ignore the first fields fields on each input line when doing comparisons, where fields is
a positive decimal integer. A field is the maximal string matched by the basic regular
expression:
[[:blank:]]*[^[:blank:]]*
If fields specifies more fields than appear on an input line, a null string will be used for
comparison.

-s char

Ignore the first chars characters when doing comparisons, where chars is a positive
decimal integer. If specified in conjunction with the -f option, the first chars characters
after the first fields fields will be ignored. If chars specifies more characters than remain
on an input line, a null string will be used for comparison.

-n

Equivalent to -f fields with fields set to n.

U.HARITHA

36

LINUX UTILITIES
+m

Equivalent to -s chars with chars set to m.

input_file A path name of the input file. If input_file is not specified, or if the input_file is -, the
standard input will be used.
output_file A path name of the output file. If output_file is not specified, the standard output will be
used. The results are unspecified if the file named by output_file is the file named by
input_file.
EXAMPLES
uniq myfile1.txt > myfile2.txt
Removes duplicate lines in the first file1.txt and outputs the results to the second file.
6. comm: Compare two sorted files line-by-line.
SYNTAX
comm [OPTION]... FILE1 FILE2
DESCRIPTION: Compare sorted files FILE1 and FILE2 line-by-line.With no options,
comm produces three-column output. Column one contains lines unique to FILE1, column
two contains lines unique to FILE2, and column three contains lines common to both files.
Each of these columns can be suppressed individually with options.
OPTIONS
-1

suppress column 1 (lines unique to FILE1)

-2

suppress column 2 (lines unique to FILE2)

-3

suppress column 3 (lines that appear in both files)

--check-order
--nocheck-order
--outputdelimiter=STR

U.HARITHA

check that the input is correctly sorted, even if all input lines are
pairable
do not check that the input is correctly sorted
separate columns with string STR

37

LINUX UTILITIES
--help
--version

display a help message, and exit.


output version information, and exit.

EXAMPLES
1. comm -12 myfile1.txt myfile2.txt
Print only the lines present in both myfile1.txt and myfile2.txt.
2. comm -3 myfile1.txt myfile2.txt
Print only the lines that are present in myfile1.txt and not myfile2.txt, and vice versa.
7. cmp :Compare two files byte by byte.
SYNTAX
cmp [OPTION]... FILE1 [FILE2 [SKIP1 [SKIP2]]]
OPTIONS
The optional SKIP1 and SKIP2 specify the number of bytes to skip at the beginning of each
file (zero by default).
SKIP values may be followed by the following multiplicative suffixes:
kB kilobytes 1000
K

kibibytes 1024

MB megabytes 1,000,000
M mebibytes 1,048,576
GB gigabytes 1,000,000,000
G

gibibytes 1,073,741,824

... and so on for T, P, E, Z, Y.

U.HARITHA

38

LINUX UTILITIES
If a FILE is specified as '-' or not specified, data is read from standard input. cmp's exit status
is 0 if inputs are the same, 1 if different, or 2 if the program encounters a problem.
ADDITIONAL OPTIONS:
-b, --print-bytes

print differing bytes.

-i, --ignore-initial=SKIP

skip first SKIP bytes of both files.

-i,--ignore-initial=SKIP1:SKIP2

skip first SKIP1 bytes of FILE1 and first SKIP2 bytes of


FILE2

-l, --verbose

output byte numbers and differing byte values.

-n, --bytes=LIMIT

compare at most LIMIT bytes.

-s, --quiet, --silent

suppress all normal output.

--help

display a help message and exit.

-v, --version

output version information and exit.

EXAMPLES
cmp file1.txt file2.txt
Compares file1 to file2, reading each file byte-by-byte and comparing them until one of the
byte pairs is not equal. When a difference is found, it will output the location in the file where
the difference was found, and exit. Example output:
file.txt file2.txt differ: char 1011, line 112
8. diff: Displays two files and prints the lines that are different.
SYNTAX
diff [OPTION]... FILES
OPTIONS
--normal

output a normal diff (This is the default).

-q, --brief

report only when files differ.

U.HARITHA

39

LINUX UTILITIES
-s, --report-identical-files

report when two files are the same.

-c, -C NUM, --context[=NUM]

output NUM (default 3) lines of copied context.

-u, -U NUM, --unified[=NUM]

output NUM (default 3) lines of unified context.

-e, --ed

output an ed script.

-n, --rcs

output an RCS-format diff.

-y, --side-by-side

output in two columns.

-W, --width=NUM

output at most NUM (default 130) print columns.

--left-column

output only the left column of common lines.

--suppress-common-lines

do not output common lines.

-p, --show-c-function

show which C function each change is in.

-F, --show-function-line=RE

show the most recent line matching RE.

--label LABEL

use LABEL instead of file name (this option can be


repeated).

-t, --expand-tabs

expand tabs to spaces in output.

-T, --initial-tab

make tabs line up by prepending a tab.

--tabsize=NUM

tab stops every NUM (default 8) print columns.

--suppress-blank-empty

suppress space or tab before empty output lines.

-l, --paginate

pass output through pr to paginate it

-r, --recursive

recursively compare any subdirectories found.

-N, --new-file

treat absent files as empty.

--unidirectional-new-file

treat absent first files as empty.

--ignore-file-name-case

ignore case when comparing file names.

--no-ignore-file-name-case

consider case when comparing file names.

-x, --exclude=PAT

exclude files that match PAT.

-X, --exclude-from=FILE

exclude files that match any pattern in FILE.

-S, --starting-file=FILE

start with FILE when comparing directories.

--from-file=FILE1

compare FILE1 to all operands; FILE1 can be a directory.

U.HARITHA

40

LINUX UTILITIES
--to-file=FILE2

compare all operands to FILE2; FILE2 can be a directory.

-i, --ignore-case

ignore case differences in file contents.

-E, --ignore-tab-expansion

ignore changes due to tab expansion.

-b, --ignore-space-change

ignore changes in the amount of white space.

-w, --ignore-all-space

ignore all white space.

-B, --ignore-blank-lines

ignore changes whose lines are all blank.

-I, --ignore-matching-lines=RE

ignore changes whose lines all match RE.

-a, --text

treat all files as text.

-d, --minimal

try hard to find a smaller set of changes.

--horizon-lines=NUM

keep NUM lines of the common prefix and suffix.

--speed-large-files

assume large files and many scattered small changes.

--help

display a help message and exit.

-v, --version

output version information and exit.

FILES are 'FILE1 FILE2' or 'DIR1 DIR2' or 'DIR FILE...' or 'FILE... DIR'. If --from-file or -to-file is given, there are no restrictions on FILE(s). If a FILE is '-', diff reads from standard
input. Exit status is 0 if inputs are the same, 1 if different, 2 if diff encounters any trouble.
EXAMPLES
diff help dir2
Compares the directory named help with the directory named dir2

9. join: Joins the lines of two files which share a common field of data.
SYNTAX
join [OPTION]... FILE1 FILE2
OPTIONS
-a FILENUM

also print unpairable lines from file FILENUM, where FILENUM is 1 or 2,


corresponding to FILE1 or FILE2

U.HARITHA

41

LINUX UTILITIES
-e EMPTY

replace missing input fields with EMPTY

-i, --ignore-case ignore differences in case when comparing fields


-j FIELD

equivalent to "-1 FIELD -2 FIELD".

-o FORMAT

obey FORMAT while constructing output line.

-t CHAR

use CHAR as input and output field separator.

-1 FIELD

join on this FIELD of file 1.

-2 FIELD

join on this FIELD of file 2.

--check-order check that the input is correctly sorted, even if all input lines are pairable.
--nocheck-order do not check that the input is correctly sorted.
--help
--version

display a help message and exit.


display version information and exit.

EXAMPLES
If we have a file, myfile1.txt, whose contents are:
1 India 2 US 3 Ireland 4 UK 5 Canada
...and another file, myfile2.txt, whose contents are:
1 NewDelhi 2 Washington 3 Dublin 4 London 5 Toronto
The common fields are the fields which begin with the same number. We can join the
contents using the following command:
join myfile1.txt myfile2.txt
...which outputs the following to standard output:
1 India NewDelhi 2 US Washington 3 Ireland Dublin 4 UK London 5 Canada Toronto
If we wanted to create a new file with the joined contents, we could use the following
command:
join myfile1.txt myfile2.txt > myjoinedfile.txt

U.HARITHA

42

LINUX UTILITIES
...which directs the output into a new file called myjoinedfile.txt, containing the same output
as the example above.

10. grep: Searches for a pattern in a file.


SYNTAX
grep [ -E | -F ] [ -i ] [ -h ] [ -H ] [ -L ] [ -r | -R ] [ -s ][ -u ] [ -v ] [ -w ] [ -x ] [ -y ] [ [ [ -b ] [ n ] ] | [ -c | -l | -q ] ] [ -p [ Separator ] ] { [ -e PatternList ... ] [ -f PatternFile ... ] | PatternList
... } [ File ... ]
DESCRIPTION
The grep command searches for the pattern specified by the Pattern parameter and write
each matching line to standard output. The patterns are limited regular expressions in the
style of the ed or egrep command. The grep command uses a compact non-deterministic
algorithm.
Notes:
1. Do not run the grep command on a special file because it produces unpredictable
results. Input lines should not contain the NULL character.
2. Input files should end with the newline character.
3. The newline character will not be matched by the regular expressions.
4. Although some flags can be specified simultaneously, some flags override others. For
example, the -l option takes precedence over all other flags. And if you specify both
the -E and -F flags, the last one specified takes priority.
OPTIONS:
Item
-c

Description
Displays only a count of matching lines.

-e PatternList

Specifies one or more search patterns. This works like a simple pattern but is
useful when the pattern begins with a - (minus). Patterns should be separated by
a new-line character. A NULL pattern can be specified by two adjacent newline characters or a quotation mark followed by a new-line character ("\n). Each
pattern is treated like a basic regular expression (BRE) unless the -E or -F flag
is also specified. Multiple -e and -f flags are accepted by grep. All of the
specified patterns are used when matching lines, but the order of evaluation is
unspecified.

-F

Treats each specified pattern as a string instead of a regular expression. A

U.HARITHA

43

LINUX UTILITIES
Item

Description
NULL string matches every line.
Note: The grep command with the -F flag is the same as the fgrep command,
except that error and usage messages are different and the -s flag functions
differently.

-f PatternFile

Specifies a file containing search patterns. Each pattern should be separated by


a new-line character, and an empty line is considered a NULL pattern. Each
pattern is treated like a basic regular expression (BRE), unless the -E or -F flag
is also specified.

-i

Ignores the case (uppercase or lowercase) of letters when making comparisons.

-l

Lists just the names of files (once) which contain matching lines. Each file
name is separated by a new-line character. If standard input is searched, a path
name of (StandardInput) is returned. The -l flag with any combination of the -c
and -n flags behaves like the -l flag only.

-n

Precedes each line with the relative line number in the file. Each file starts at
line 1, and the line counter is reset for each file processed.

-v

Displays all lines not matching the specified pattern.

-x

Displays lines that match the specified pattern exactly with no additional
characters.

Exit Status
This command returns the following exit values:
Item Description
0

A match was found.

No match was found.

>1

A syntax error was found or a file was inaccessible (even if matches were found).

Examples
1. To use a pattern that contains some of the pattern-matching characters *, ^, ?, [, ], \(, \), \{,
and \}, enter:
grep "^[a-zA-Z]" pgm.s
This displays every line in pgm.s whose first character is a letter.
2. To display all lines that do not match a pattern, enter:

U.HARITHA

44

LINUX UTILITIES
grep -v "^#" pgm.s
This displays every line in pgm.s whose first character is not a # (pound sign).
3. To display all lines in the file1 file that match either the abc or xyz string, enter:
grep -E "abc|xyz" file1
4. To search for a $ (dollar sign) in the file named test2, enter:
grep \\$ test2
The \\ (double backslash) characters are necessary in order to force the shell to pass a
\$ (single backslash, dollar sign) to the grep command. The \ (single backslash)
character tells the grep command to treat the following character (in this example the
$) as a literal character rather than an expression character. Use the fgrep command to
avoid the necessity of using escape characters such as the backslash.
5. To search recursively through /tmp to find files which have the word IBM without
recursing through links pointing to directories, type:
grep R IBM /tmp
OR
grep r -H IBM /tmp
6. To search recursively through /tmp to find files which have the word IBM and recurse
through links as well, type:
grep r IBM /tmp
OR
grep -R -L IBM /tmp

11. sed :
12. awk :

1.7 Text Processing Utilities and Backup Utilities


Text processing utilities:
1. sort :
2. join :

U.HARITHA

45

LINUX UTILITIES
3. cut :
4. paste : Merge corresponding or subsequent lines of files.
SYNTAX
paste [-s] [-d list] file
OPTIONS
-s

Concatenate all of the lines of each separate input file in command line order.

-d list

Unless a backslash character (\) appears in list, each character in list is an element specifying
a delimiter character.

file

A path name of an input file. If - is specified for one or more of the file s, the standard input
will be used; the standard input will be read one line at a time, circularly, for each instance of
-. Implementations support pasting of at least 12 file operands.

Examples
ls | paste - - - Take the input from ls and paste that input into four columns.
5. tr: Tr stands for translate or transliterate. The tr utility in unix or linux system is used to
translate, delete or squeeze characters.
SYNTAX : The syntax of tr command is
tr [options] set1 [set2]
OPTIONS

-c
-d
-s
-t

complements the set of characters in string.


deletes the characters in set1
repeated characters listed in the set1 with single occurrence
truncates set1

EXAMPLES:
1. Convert lower case letters to upper case
The following tr command translates the lower case letters to capital letters in the give
string:
> echo "linux dedicated server" | tr "[:lower:]" "[:upper:]"
LINUX DEDICATED SERVER
> echo "linux dedicated server" | tr "[a-z]" "[A-Z]"
LINUX DEDICATED SERVER

U.HARITHA

46

LINUX UTILITIES

3. Replace non-matching charecters


The -c option is used to replace the non-matching characters with another set of
characters.
> echo "unix" | tr -c "u" "a"
uaaa
In the above example, except the character "c" other characters are replaced with "a"

4. Delete non-printable charecters


The -d option can be used to delete characters. The following example deletes all the
non-printable characters from a file.
> tr -cd "[:print:]" < filename
5. Squeezing characters
You can squeeze more than one occurrence of continuous characters with single
occurrence. The following example squeezes two or more successive blank spaces into a
single space.
> echo "linux

server" | tr -s " "

linux server
Here you can replace the space character with any other character by specifying in set2.
> "linux

server" | tr -s " " ","

linux,server

6. Delete charecters
The following example removes the word linux from the string.
> echo "linuxserver" | tr -d "linux"
Server

Backup Utilities:
1. tar: The tar (i.e., tape archive) command is used to convert a group of files into an
archive.
SYANTAX:
tar <operation> [options]

U.HARITHA

47

LINUX UTILITIES
OPERATIONS:
[-]A --catenate --concatenate
[-]c --create
[-]d --diff --compare
[-]r --append
[-]t --list
[-]u update
[-]x --extract --get
--delete
OPTIONS:
-C, --directory DIR
-f, --file F
-j, --bzip2
-p, --preserve-permissions
-v, --verbose
-z, --gzip
EXAMPLES
1. tar -xvf foo.tar

verbosely extract foo.tar


2. tar -xzf foo.tar.gz

extract gzipped foo.tar.gz


3. tar -cjf foo.tar.bz2 bar/

create bzipped tar archive of the directory bar called foo.tar.bz2


4. tar -xjf foo.tar.bz2 -C bar/

extract bzipped foo.tar.bz2 after changing directory to bar


5. tar -xzf foo.tar.gz blah.txt

extract the file blah.txt from foo.tar.bz2


2. cpio :
cpio command is used to process archive files (for example, *.cpio or *.tar files).cpio
stands for copy in, copy out.cpio performs the following three operations.

Copying files to an archive

Extracting files from an archive

Passing files to another directory tree

U.HARITHA

48

LINUX UTILITIES
cpio takes the list of files from the standard input while creating an archive, and sends the
output to the standard output.
1. Create *.cpio Archive File
You can create a *.cpio archive that contains files and directories using cpio ov
$ cd objects
$ ls
file1.o file2.o file3.o
$ ls | cpio -ov > /tmp/object.cpio
As seen above, the ls command passes the three object filenames to cpio command and
cpio generates the object.cpio archive.
2. Extract *.cpio Archive File
cpio extract: To extract a given *.cpio file, use cpio -iv as shown below.
$ mkdir output
$ cd output
$ cpio -idv < /tmp/object.cpio
3. Create *.cpio Archive with Selected Files
The following example creates a *.cpio archive only with *.c files.
$ find . -iname *.c -print | cpio -ov >/tmp/c_files.cpio
4. Create *.tar Archive File using cpio F
We already know how to use the tar command effectively.
Did you know that you can also use cpio command to create tar files as shown below?
$ ls | cpio -ov -H tar -F sample.tar
As seen above, instead of redirecting the standard output you can mention the
output archive filename with the option -F.

U.HARITHA

49

LINUX UTILITIES
5. Extract *.tar Archive File using cpio command
You can also extract a tar file using cpio command as shown below.
$ cpio -idv -F sample.tar
6.

View the content of *.tar Archive File


To view the content of *.tar file, do the following.

$ cpio -it -F sample.tar


7.

Create a *.cpio Archive with the Original files that a Symbolic Link Points

cpio archive can be created with the original files that a symbolic link is referring to as
shown below.
$ ls | cpio -oLv >/tmp/test.cpio
8.

Preserve the File Modification Time while restoring *.cpio

The modification time of the files can be preserved when we are restoring the cpio
archive files as shown below.
$ ls | cpio -omv >/tmp/test.cpio
9.

Copy Directory Tree from One to Another


cpio allows you to copy one directory contents into another directory without creating an

intermediate archive. It reads the file list from the standard input and pass it to the target
directory.
The example below copies the files and sub-directories of objects directory into /mnt/out
directory.
$ mkdir /mnt/out
$ cd objects
$ find . -depth | cpio -pmdv /mnt/out
In the above example:

cpio option -p makes cpio to use pass through mode. Its like piping cpio -o into cpio -i.

cpio option -d creates leading directories as needed in the target directory.

U.HARITHA

50

Potrebbero piacerti anche