Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Linux Utilities
Show all.
-b
-e
-E
-n
-s
If the output has multiple empty lines it replaces it with one empty
line.
-T
-v
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.
-i
-r (or) -R
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]
-b
-f
-p
same
as
--preserve=mode,
ownership,
timestamps.
--preserve[=ATTR_LIST]
--no-preserve=ATTR_LIST
--parents
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.
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
EXAMPLE:
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
-a
-d
-p
-u
-i
-ltr
-lSr
EXAMPLE:
1. Display root directory contents:
ls /
lists the contents of root directory.
2.
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.
-P
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
-p
-v
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
EXAMPLES:
1. To delete/remove a directory
rmdir tmp
rmdir command will remove/delete the directory tmp if the directory is empty.
2.
U.HARITHA
LINUX UTILITIES
This command recursively removes the contents of all subdirectories of the tmp
directory, prompting
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 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.
Execute:
User with execute permissions can run a file as a program.
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
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.
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
Ref
No permission
---
Execute permission
--x
Write permission
-w-
-wx
Read permission
r--
r-x
rw-
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 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.
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:
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
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
U.HARITHA
14
LINUX UTILITIES
-A or e
-d
-e
-f
-j
-l
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.
Specify the signal to send. The signal may be given as a signal name or number.
-l
-pid
-9
U.HARITHA
15
LINUX UTILITIES
EXAMPLE:
Step by Step process:
increment
command
argument
U.HARITHA
16
LINUX UTILITIES
EXAMPLE:
nice +13 pico myfile.txt - runs the pico command on myfile.txt with an increment of +13.
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
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
-k
-s
-f filename
-m
-t time
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
-r
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.
U.HARITHA
18
LINUX UTILITIES
OPTIONS:
-a, --all
-B, --block-size=SIZE
--total
-h, --human-readable
-H, --si
-i, --inodes
-k
like --block-size=1K.
-l, --local
--no-sync
-P, --portability
--sync
-t, --type=TYPE
-T, --print-type
-x, --exclude-type=TYPE
-v
--help
--version
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
--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
-b, --bytes
-c, --total
-H
-h,--human-
readable
-k
like --block-size=1K.
-l, --count-links
-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
--time-
style=STYLE
--help
--version
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
U.HARITHA
21
LINUX UTILITIES
OPTIONS:
-V, --version
-h, --help
-v, --verbose
Operate verbosely.
-a, --all
-F, --fork
-f, --fake
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.
-r
-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
-a
U.HARITHA
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.
-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
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
25
LINUX UTILITIES
-d
-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
-l user
then user will be sent to the remote system as the value for the ENVIRON
variable USER.
-n file
EXAMPLES:
1. telnet host.com
The above example would open a telnet session to the domain host.com.
U.HARITHA
26
LINUX UTILITIES
OPTIONS:
-4
-6
-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
-e
Disables command editing and history support, if it was compiled into the ftp
executable. Otherwise, does nothing.
-g
-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
-E
-L
-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
-h
-i
-l
-m
Assumes that the User parameter specifies a user ID (used for discretionary access
control), not a user login name.
-p
-q
-s
-w
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.
finger brown@alcatraz
Information similar to the following is displayed:
Login name: brown
Directory: /home/brown
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.
-v, --verbose
--help
--version
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
-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:
+
None
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
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.
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
-c
-d
-f
Ignores caps
-g
-i
-m
-M
Treats the first three letters in the line as a month (such as may.)
-n
-o
-r
-s
-u
-z
+fields
filename
-o outputfile
U.HARITHA
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
-c, --characters=LIST
-d, --delimiter=DELIM
-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
-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
U.HARITHA
36
LINUX UTILITIES
+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
-2
-3
--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
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
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
-i, --ignore-initial=SKIP
-i,--ignore-initial=SKIP1:SKIP2
-l, --verbose
-n, --bytes=LIMIT
--help
-v, --version
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
-q, --brief
U.HARITHA
39
LINUX UTILITIES
-s, --report-identical-files
-e, --ed
output an ed script.
-n, --rcs
-y, --side-by-side
-W, --width=NUM
--left-column
--suppress-common-lines
-p, --show-c-function
-F, --show-function-line=RE
--label LABEL
-t, --expand-tabs
-T, --initial-tab
--tabsize=NUM
--suppress-blank-empty
-l, --paginate
-r, --recursive
-N, --new-file
--unidirectional-new-file
--ignore-file-name-case
--no-ignore-file-name-case
-x, --exclude=PAT
-X, --exclude-from=FILE
-S, --starting-file=FILE
--from-file=FILE1
U.HARITHA
40
LINUX UTILITIES
--to-file=FILE2
-i, --ignore-case
-E, --ignore-tab-expansion
-b, --ignore-space-change
-w, --ignore-all-space
-B, --ignore-blank-lines
-I, --ignore-matching-lines=RE
-a, --text
-d, --minimal
--horizon-lines=NUM
--speed-large-files
--help
-v, --version
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
U.HARITHA
41
LINUX UTILITIES
-e EMPTY
-o FORMAT
-t CHAR
-1 FIELD
-2 FIELD
--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
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.
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
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
-i
-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
-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
>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 :
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
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
linux server
Here you can replace the space character with any other character by specifying in set2.
> "linux
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
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.
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.
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.
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.
U.HARITHA
50