Sie sind auf Seite 1von 61

Linux Fundamentals Commands

For

Created by: Mangesh Abnave


Part I V.1.0
LINUX FUNDAMENTALS | Mangesh Abnave
A. Find Command

1. Find Files Using Name in Current Directory:-


find . -name test.txt (For e.g. I took the name test.txt you can type any file name which you would like to
search

2. Find Files under Home Directory:


find /etc -name hosts

3. Find Files Using Name and Ignoring Case:-


touch /etc/MANUAL
find . -iname manual

4. Find Directories Using Name:


find / -type d -iname siemens

LINUX FUNDAMENTALS | Mangesh Abnave


5. Find all Configuration Files in Directory:-
find . -type f -name "*.conf"

6. Find Files With 777 Permissions:-


# find . -type f -perm 0777 -print

7. Find Files without 777 Permissions:-


# find . -type f ! -perm 0777

8. Find Read Only Files:-


# find / -perm /u=r

9 Find Executable Files:


# find / -perm /a=x

LINUX FUNDAMENTALS | Mangesh Abnave


10. Find all Empty Files:
# find /tmp -type f -empty

11. Find all Empty Directories:


# find /tmp -type d -empty

12. File all Hidden Files:-


# find /tmp -type f -name ".*"

13. Find Single File Based on User:-


To find all or single file called amdocs.txt under / root directory of owner root.
# find / -user root -name siemens*

LINUX FUNDAMENTALS | Mangesh Abnave


14. Find all Files Based on User:-
To find all files that belongs to user amdocs under /home directory.
# find /home -user mangesh1

15. Find all Files Based on Group:


To find all files that belongs to group Developer under /home directory.
# find /home -group developer

16. Find Last Modified Files:-


3 Parameters can be passed into this type of find command: mmin, mtime, newer

mmin: find files where file was last modified n minutes ago.
Find /test123 –mmin 2: Meaning of this command is the files which was modified 2 mins ago in the directory
test123

mtime: find files where file was last modified n*24 hours ago

LINUX FUNDAMENTALS | Mangesh Abnave


newer: find files which was modified more recently than file

17. Find Last Accessed Files:


Find file which was last accessed n minutes ago where access time is newer then modified time.

Finds files where Access time is newer then modified time

Finds files which were accessed in last n*24 ago. Any fractional part is ignored, so to match -atime +1(More than
24 hrs) a file has to have been accessed at least two days ago. find -atime 3 ; finds files accessed 72 hrs ago (
3*24 )

LINUX FUNDAMENTALS | Mangesh Abnave


18. Find Changed Files:-

Finds files where file’s status Change time is newer than its modified time

Find files whose status changed time in last n*24 ago. any fractional part is ignored.

Find files whose status changed time n minutes ago

Find Command Summary:


Here are the 14 Ways to find files in UNIX and Linux
1. By file name -name
2. Using User/group identification -uid, -user, -gid, -group, -nouser, -nogroup
3. By file Modified time -mmin, -mtime, -newer
4. Using last accessed time -amin, -atime, -anewer
5. Using File Status Change time -cmin, -ctime, -cnewer, -used
6. Based on file Type -empty, -executable, -readable, -writable
7. By file type -type
8. Using File Permissions -perm
9. Using File size -size, -1M Less than 1 MB, +1M More than 1 MB
10. By path name -path
11. By number of hard & soft links -links and provide number is links
12. By Inode number -inum
13. File System type -fstype
14. Using regex pattern -regex

LINUX FUNDAMENTALS | Mangesh Abnave


Tape Archiver Command:

Syntax:

tar [options] [archive-file] [file or directory to be archived]

Options:

-c : Creates Archive

-x : Extract the archive

-f : creates archive with given filename

-t : displays or lists files in archived file

-u : archives and adds to an existing archive file

-v : Displays Verbose Information

-A : Concatenates the archive files

-z : zip, tells tar command that create tar file using gzip

-j : filter archive tar file using tbzip

-W : Verify a archive file

-r : update or add file or directory in already existed .tar file

1. Create tar Archive File

tar -cvf mangeshhome.tar /home/Mangesh

2. Create tar.gz Archive File

To create a compressed gzip archive file we use the option as z

# tar -cvzf mangeshhome.tar.gz /home/mangesh


OR
# tar -cvzf mangeshhome.tgz /home/Mangesh

LINUX FUNDAMENTALS | Mangesh Abnave


3. Create tar.bz2 Archive File

The bz2 feature compress and create archive file less than the size of the gzip. The bz2 compression takes more
time to compress and decompress files as compared to gzip which takes less time. To create highly compressed
tar file we use option as j

# tar cvfj mangeshhome.tar.bz2 /home/mangesh


OR
# tar cvfj mangeshhome.tar.tbz /home/mangesh
OR
# tar cvfj mangeshhome.tar.tb2 /home/Mangesh

4. Untar tar Archive File

## Untar files in Current Directory ##


# tar -xvf mangeshhome.tar

## Untar files in specified Directory ##


# tar -xvf mangeshhome.tar -C /root/test123/

LINUX FUNDAMENTALS | Mangesh Abnave


5. Uncompressed tar.gz Archive File:-

# tar -xvf mangeshhome.tar.gz

6. Uncompressed tar.bz2 Archive File:

tar -xvf mangeshhome.tar.bz2

7. List Content of tar, tar.gz, tar.bz2 Archive File:

To list the contents of tar archive file, just run the following command with option t (list content).

tar -tvf mangeshhome.tar

8. Untar Single file from tar File:

# tar -xvf mangeshhome.tar home/Mangesh/Pictures


OR
# tar --extract --file=mangeshhome.tar home/Mangesh/Pictures

LINUX FUNDAMENTALS | Mangesh Abnave


Same thing could be done for the .tar.gz and tar.bz2.

# tar -zxvf mangeshhome.tar.gz home/mangesh/Pictures


OR
# tar --extract --file=mangeshhome.tar.gz home/mangesh/Pictures

# tar -jxvf mangeshhome.tar.bz2 home/mangesh/Pictures


OR
# tar --extract --file=mangeshhome.tar.bz2 home/mangesh/Pictures

9. Untar multiple files from tar, tar.gz and tar.bz2 File

# tar -xvf mangeshhome.tar "home/mangesh/Pictures" "home/mangesh/Desktop"

# tar -zxvf mangeshhome.tar.gz "home/mangesh/Pictures" "home/mangesh/Desktop"

# tar -jxvf mangeshhome.tar.bz2 "home/mangesh/Pictures" "home/mangesh/Desktop"

10. Extract Group of Files using Wildcard:

# tar -xvf mangeshhome.tar --wildcards 'home/mangesh/D*'

# tar -zxvf mangeshhome.tar.gz --wildcards 'home/mangesh/D*'

# tar -jxvf mangeshhome.tar.bz2 --wildcards 'home/mangesh/D*'

LINUX FUNDAMENTALS | Mangesh Abnave


11. Add Files or Directories to tar Archive File:

# tar -rvf mangeshhome.tar file

# tar -rvf mangeshhome.tar testmangesh

# tar -rvf mangeshhome.tar.gz testmangesh

# tar -rvf mangeshhome.tar.bz2 testmangesh

12. How To Verify tar, tar.gz and tar.bz2 Archive File:

To verfify any tar or compressed archived file we use option as W (verify). (Note : You cannot do verification on a
compressed ( *.tar.gz, *.tar.bz2 ) archive file).

tar tvfW mangeshhome.tar

13. Check the Size of the tar, tar.gz and tar.bz2 Archive File

To check the size of any tar, tar.gz and tar.bz2 archive file, use the following command. For example the below
command will display the size of archive file in Kilobytes (KB).

tar -czf - mangeshhome.tar | wc -c

tar -czf - mangeshhome.tar.gz | wc -c

tar -czf - mangeshhome.tar.bz2 | wc –c

LINUX FUNDAMENTALS | Mangesh Abnave


14. Delete From Archive:

# tar -f mangeshhome.tar --delete file


# tar -tf mangeshhome.tar

15. Update Files Inside Archive

# echo "new text" >> file


# tar -uf mangeshhome.tar file
# rm -f file
# tar -xf mangeshhome.tar
# cat file

Same thing is applied for an directory.

LINUX FUNDAMENTALS | Mangesh Abnave


DF and DU Command Usage:

-a,--all : It includes all the dummy files also in the output which are actually having zero
block sizes.
-B,- -block-size=S : This is the option we were talking in the above para which is used to scale sizes by
SIZE like -BM prints sizes in units of 1,048,576 bytes.
– -total : It is used to display the grand total for size.
-h, - -human-readable : It print sizes in human readable format.
-H,- -si : This option is same as -h but it use powers of 1000 instead of 1024.
-i,- -inodes : This option is used when you want to display the inode information instead of block
usage.
-k : Its use is like –block-size-1k.
-l,- -local : This will display the disk usage of only local file systems.
-P,- -portability : It uses the POSIX output format.
-t,- -type=TYPE : It will only show the output of file systems having type TYPE.
-T,- -print-type : This option is used to print file system type shown in the output.
-x,- -exclude-type=TYPE : It will exclude all the file systems having type TYPE from the output.
-v : Ignored, included for compatibility reasons.
– -no-sync : This is the default setting i.e not to invoke sync before getting usage info.
– -sync : It invokes a sync before getting usage info.
– -help : It displays a help message and exit.
– -version : It displays version information and exit.

1. Check File System Disk Space Usage


df

2. Display Information of all File System Disk Space Usage


df -a

LINUX FUNDAMENTALS | Mangesh Abnave


3. Show Disk Space Usage in Human Readable Format
df -h

4. Display Information of /home File System


df -hT /home

5. Display Information of File System in Bytes


df -k

6. Display Information of File System in MB


df -m

LINUX FUNDAMENTALS | Mangesh Abnave


7. Display File System Inodes
df -i

8. Display File System Type


df -T

9. Include Certain File System Type


df -t xfs

10. Exclude Certain File System Type


df -x ext3

LINUX FUNDAMENTALS | Mangesh Abnave


11. Using – -total: This option is used to produce total for a size, used and available columns in the output.
df --total -h

12. Using – -sync : By default, the df command produces output with – -no-sync option which will not perform
the sync system call prior to reporting usage information. Now we can use – -sync option which will force a
sync resulting in the output being fully up to date.

df --sync

13. Using -l : When we run df command then by default it shows any externally mounted file systems which
include those from external NFS or Samba servers. We can hide the info of these external file systems from
output with -l option syntax of which is shown below.

df –l

LINUX FUNDAMENTALS | Mangesh Abnave


1. To find out the disk usage summary of a /home/mangesh directory tree and each of its sub directories
du /home/mangesh

2. Using “-h” option with “du” command provides results in “Human Readable Format“.
du -h /home/Mangesh

3. To get the summary of a grand total disk usage size of an directory use the option “-s” as follows.

4. Using “-a” flag with “du” command displays the disk usage of all the files and directories.

LINUX FUNDAMENTALS | Mangesh Abnave


5. Find out the disk usage of a directory tree with its subtrees in Kilobyte blocks. Use the “-k” (displays size
in 1024 bytes units).

6. To get the summary of disk usage of directory tree along with its subtrees in Megabytes (MB) only. Use the
option “-mh” as follows. The “-m” flag counts the blocks in MB units and “-h” stands for human readable
format

# du –mh /home/mangesh

7. The “-c” flag provides a grand total usage disk space at the last line.

8. The below command calculates and displays the disk usage of all files and directories, but excludes the files
that matches given pattern. The below command excludes the “.txt” files while calculating the total size of
directory. So, this way you can exclude any file formats by using flag “-–exclude“. See the output there is
no txt files entry.

LINUX FUNDAMENTALS | Mangesh Abnave


9. Display the disk usage based on modification of time, use the flag “–time” as shown below.

10. Get summary of file system using -s option


du -s /home/mandeep/test

SCP (Secure Copy):-

When you want to copy from one machine to another machine we are using built in utility called Secure Copy.

Basic Syntax of the SCP as follows:

scp source_file_name username@destination_host:destination_folder

1. scp
You can use “-v” parameter to print debug information into the screen

scp -v mangesh root@192.168.102.146:/root

I am transferring file name called Mangesh from my local server to 192.168.102.146 machine. Either I can use
the IP address or hostname of the remote machine, however the remote machine IP address should in my local
/etc/hosts

Remote Machine
User to which I want
to send the file

Remote Machine
directory where I
want to copy on
remote machine

Remote Machine IP
Address where I want
to transfer the file
Name of the file which you want to transfer
LINUX FUNDAMENTALS | Mangesh Abnave
The “-p” parameter will help you on this. An estimated time and the connection speed will appear on the
screen.

The “-C” parameter will compress your files on the go. The unique thing is the compression is only happen in
the network. When the file is arrived to the destination server, it will returning into the original size as before
the compression happen.

By default SCP using “AES-128” to encrypt files. If you want to change to another cipher to encrypt it, you can
use “-c” parameter. Take a look of this command.

The “-l” parameter will limit the bandwidth to use. It will be useful if you do an automation script to copy a lot
of file, but you don’t want the bandwidth is drained by the SCP process.

LINUX FUNDAMENTALS | Mangesh Abnave


Usually SCP is using port 22 as a default port. But for security reason, you may change the port into another
port. For example, we are using port 2249. Then the command should be like this. I am using port 22 only demo
this command.

Sometimes we need to copy directory and all files/directories inside it. It will be better if we can do it in single
command. SCP support that scenario using “-r” parameter. Transferring directory in verbose and recursive
mode.

If you choose not to see progress meter and warning / diagnostic messages from SCP, you may disable it using
“-q” parameter. Here’s the example. Trying transfer directory called mangeh1 quietly.

Copy files across 2 remote hosts:


SCP can copy files from 1 remote host to another remote host as well.
scp root@192.168.102.148:/some/remote/dir/mangesh.txt root@192.168.102.148:/some/remote/dir/

LINUX FUNDAMENTALS | Mangesh Abnave


Preserve file attributes:
The '-p' option (small case), would preserve modification times, access times, and modes from the original
file. It will preserve all the rwx permission as per the original file.

Specify identity file:


When using key based (passwordless) authentication, you would need to specify the identity file which
contains the private key. This option is directly passed to the ssh command and works the same way.
This method will only use at the time of passwordless access.

WGET:
Single file download:

The command will download single file and stores in a current directory. It also shows download progress, size,
date and time while downloading.

Download file with different name:


Using -O (uppercase) option, downloads file with different file name. Here we have given wget.zip file name as
show below.

LINUX FUNDAMENTALS | Mangesh Abnave


Download multiple file with http and ftp protocol:

Read URL’s from a file:


You can store number of URL’s in text file and download them with -i option. Below we have created tmp.txt
under wget directory where we put series of URL’s to download. Create one file named wget.txt and in that txt
file mentioned all the links from where you need download from.

Download files in background:


With -b option you can send download in background immediately after download start and logs are written in
/root/mangesh1/log.txt file.

Restrict download speed limits:


With Option –limit-rate=100K, the download speed limit is restricted to 100k and the logs will be created under
/wget/log.txt as shown below.

Restricted FTP and HTTP downloads with username and password:

With Options –http-user=username, –http-password=password & –ftp-user=username, –ftp-


password=password, you can download password restricted HTTP or FTP sites as shown below

wget --http-user=mangesh --http-password=password


http://mirrors.hns.net.in/centos/6.3/isos/x86_64/CentOS-6.3-x86_64-LiveDVD.iso

LINUX FUNDAMENTALS | Mangesh Abnave


wget --ftp-user=mangesh --ftp-password=password ftp://ftp.iinet.net.au/debian/debian-cd/6.0.5/i386/iso-
dvd/debian-6.0.5-i386-DVD-1.iso

To try a given number of times:

wget --tries=10 http://centos.mirror.net.com/centos/6.10/isos/x86_64/CentOS-6.10-x86_64-LiveDVD.iso

How to download a file from untrusted secure URL


By using this option "--no-check-certificate", We can ignore checking the validity of the certificate. This
command will work only when any certificate is deployed for any download

How to download reading URL's from a file


Read URLs from a local or external file. If - is specified as file, URLs are read from the standard input.
Put the URL into filename.txt

NETSTAT:
Listing all the LISTENING Ports of TCP and UDP connections
Listing all ports (both TCP and UDP) using netstat -a option.

LINUX FUNDAMENTALS | Mangesh Abnave


Listing TCP Ports connections
Listing only TCP (Transmission Control Protocol) port connections using netstat -at.

Listing UDP Ports connections


Listing only UDP (User Datagram Protocol) port connections using netstat -au.

Listing all LISTENING Connections


Listing all active listening ports connections with netstat -l.

Listing all TCP Listening Ports


Listing all active listening TCP ports by using option netstat -lt.

LINUX FUNDAMENTALS | Mangesh Abnave


Listing all UDP Listening Ports
Listing all active listening UDP ports by using option netstat -lu.

Listing all UNIX Listening Ports


Listing all active UNIX listening ports using netstat -lx.

Showing Statistics by Protocol


Displays statistics by protocol. By default, statistics are shown for the TCP, UDP, ICMP, and IP protocols. The -s
parameter can be used to specify a set of protocols.

Showing Statistics by TCP Protocol:


Showing statistics of only TCP protocol by using option netstat -st.

LINUX FUNDAMENTALS | Mangesh Abnave


Showing Statistics by UDP Protocol:

Displaying Service name with PID:


Displaying service name with their PID number, using option netstat -tp will display “PID/Program Name”.

Displaying Kernel IP routing


Display Kernel IP routing table with netstat and route command.

Showing Network Interface Transactions


Showing network interface packet transactions including both transferring and receiving packets with MTU size

LINUX FUNDAMENTALS | Mangesh Abnave


Showing Kernel Interface Table
Showing Kernel interface table, similar to ifconfig command.

Displaying IPv4 and IPv6 Information


Displays multicast group membership information for both IPv4 and IPv6.

Print Netstat Information Continuously


To get netstat information every few second, then use the following command, it will print netstat information
continuously, say every few seconds.

Finding Listening Programs


Find out how many listening programs running on a port.

LINUX FUNDAMENTALS | Mangesh Abnave


If you don’t want only any one of those three items ( ports, or hosts, or users ) to be resolved, use following
commands.

# netstat -a --numeric-ports

# netstat -a --numeric-hosts

# netstat -a --numeric-users

When you don’t want the name of the host, port or user to be displayed, use netstat -n option. This will display
in numbers, instead of resolving the host name, port name, user name.

This also speeds up the output, as netstat is not performing any look-up.

# netstat –an

IOSTAT:

%user Show the percentage of CPU utilization that occurred while executing at the user (application) level.

Show the percentage of CPU utilization that occurred while executing at the user level
%nice
with nice priority.

%system Show the percentage of CPU utilization that occurred while executing at the system (kernel) level.

Show the percentage of time that the CPU or CPUs were idle during which the system had an
%iowait
outstanding disk I/O request.

LINUX FUNDAMENTALS | Mangesh Abnave


Show the percentage of time spent in involuntary wait by the virtual CPU or CPUs while the
%steal
hypervisor was servicing another virtual processor.

Show the percentage of time that the CPU or CPUs were idle and the system did not have an
%idle
outstanding disk I/O request.

Device This column gives the device (or partition) name as listed in the /dev directory.

tps Indicate the number of transfers per second that were issued to the device. A
transfer is an I/O request to the device. Multiple logical requests can be combined
into a single I/O request to the device. A transfer is of indeterminate size.

Blk_read/s(kB_read/s, Indicate the amount of data read from the device expressed in a number of blocks
MB_read/s) (kilobytes, megabytes) per second. Blocks are equivalent to sectors and therefore
have a size of 512 bytes.

Blk_wrtn/s(kB_wrtn/s, Indicate the amount of data written to the device expressed in a number of blocks
MB_wrtn/s) (kilobytes, megabytes) per second.

Blk_read(kB_read, The total number of blocks (kilobytes, megabytes) read.


MB_read)

Blk_wrtn(kB_wrtn, The total number of blocks (kilobytes, megabytes) written.


MB_wrtn)

rrqm/s The number of read requests merged per second that were queued to the device.

wrqm/s The number of write requests merged per second that were queued to the device.

r/s The number (after merges) of read requests completed per second for the device.

w/s The number (after merges) of write requests completed per second for the device.

rsec/s(rkB/s, rMB/s) The number of sectors (kilobytes, megabytes) read from the device per second.

wsec/s(wkB/s, wMB/s) The number of sectors (kilobytes, megabytes) written to the device per second.

avgrq-sz The average size (in sectors) of the requests that were issued to the device.

avgqu-sz The average queue length of the requests that were issued to the device.

await The average time (in milliseconds) for I/O requests issued to the device to be served.
This includes the time spent by the requests in queue and the time spent servicing
them.

LINUX FUNDAMENTALS | Mangesh Abnave


r_await The average time (in milliseconds) for read requests issued to the device to be
served. This includes the time spent by the requests in queue and the time spent
servicing them.

w_await The average time (in milliseconds) for write requests issued to the device to be
served. This includes the time spent by the requests in queue and the time spent
servicing them.

svctm The average service time (in milliseconds) for I/O requests that were issued to the
device. Warning! Do not trust this field anymore! This field will be removed in a
future sysstat version.

%util Percentage of CPU time during which I/O requests were issued to the device
(bandwidth utilization for the device). Device saturation occurs when this value is
close to 100%.

iostat uses the files below to create reports.

/proc/stat contains system statistics.


/proc/uptime contains system uptime.
/proc/diskstats contains disks statistics.
/sys contains statistics for block devices.
/proc/self/mountstats contains statistics for network filesystems.
/dev/disk contains persistent device names.

CPU STATISTICS:
In CPU statistics, use iostat –c command. The advantage of this command is, you can generate the CPU
utilization report.

If you want to see CPU utilization in 4 seconds interval with 5 times report, then the syntax will be

LINUX FUNDAMENTALS | Mangesh Abnave


DISK INPUT-OUTPUT STATISTICS:
When you want to see the performance of disk input-output statistics, and then use this syntax as follows. The
advantage of this command is that you can display device utilization report using this command.

If you want to show disk input-output under /dev/sda1 and /dev/sda3 only with 3 seconds interval and 4 times
report, here /dev/sda1 and /dev/sda3 are two type of devices.

NETWORK STATISTICS:
This section is very interesting because this section gives you the information about the network file system.

If you use iostat –N command then it gives a different output, because N displays the registered device which
mapped between devices

LINUX FUNDAMENTALS | Mangesh Abnave


DISPLAY VALUE IN MEGABYTES AND KILOBYTES:
Sometimes you need to display the variable in megabytes and the syntax format of this command given below.
This section is very useful because a variation of –m or –k commands, you can display the device statistics in
megabyte/seconds or kilobyte/seconds.

If you want to display kilobytes in 3 seconds interval with 2 times report, syntax is given below

You can also display n number of parameter, by using –x command. This command helps us to display the
extended statistics. This section is also working with the older kernel.

INPUT-OUTPUT STATISTICS FOR A SINGLE DEVICE:

LINUX FUNDAMENTALS | Mangesh Abnave


This section generates the information about the related input-output statistics for a single device by using –p
sda command. Using this command you can display all partition of a device. Here sda is one type of device
name. The following syntax

TIME STATISTICS:
Using –t command you can display the timestamp information for any type of system. The advantage of this
command is that it can display the time for each report generation. Syntax format of this section given below:

DISPLAY BLOCK DEVICE:


You can also display all block devices with their partition by using all command and the syntax format is

VMSTAT:

LINUX FUNDAMENTALS | Mangesh Abnave


Procs:

r The number of processes waiting for run time.

b The number of processes in uninterruptible sleep.

Memory:

swpd The amount of virtual memory used.

free The amount of idle memory.

buff The amount of memory used as buffers.

cache The amount of memory used as cache.

inact The amount of inactive memory. (-a option).

active The amount of active memory. (-a option).

Swap:

si Amount of memory swapped in from disk (per second).

so Amount of memory swapped to disk (per second).

IO:

bi Blocks received from a block device (blocks per second).

bo Blocks sent to a block device (blocks/s).

System:

in The number of interrupts per second, including the clock.

cs The number of context switches per second.

CPU: (values expressed in percentages of CPU time)

us Time spent running non-kernel code. (user time, including nice time)

sy Time spent running kernel code. (system time)

LINUX FUNDAMENTALS | Mangesh Abnave


id Time spent idle. Prior to Linux 2.5.41, this includes IO-wait time.

wa Time spent waiting for IO. Prior to Linux 2.5.41, included in idle.

st Time stolen from a virtual machine. Prior to Linux 2.6.11, unknown.

Field Description For Disk Mode

Reads:

total Total reads completed successfully

merged grouped reads (resulting in one I/O)

sectors Sectors read successfully

ms milliseconds spent reading

Writes:

total Total writes completed successfully

merged grouped writes (resulting in one I/O)

sectors Sectors written successfully

ms milliseconds spent writing

IO:

cur I/O in progress

s seconds spent for I/O

Files used to get the data by vmstat command


/proc/meminfo
/proc/stat
/proc/*/stat

To execute every 2 seconds for 10 times, do the following. You don’t need to press Ctrl-C in this case. After
executing 10 times, it will stop automatically.

LINUX FUNDAMENTALS | Mangesh Abnave


Run vmstat command and display timestamp of each execution.

Listing memory as active and inactive.

Active memory refers to memory that is currently is used by processes running on the system.
Inactive memory refers to memory that was allocated to a process which is no longer running.
So inactive memory isn’t actively in use but is not freed up either.

View disk statistics.

We can use the -d option with the vmstat command to view disk statistics for the system.

Reads
total: Total reads completed successfully
merged: grouped reads (resulting in one I/O)
sectors: Sectors read successfully
ms: milliseconds spent reading

Writes
total: Total writes completed successfully
merged: grouped writes (resulting in one I/O)
sectors: Sectors written successfully

LINUX FUNDAMENTALS | Mangesh Abnave


ms: milliseconds spent writing

IO
cur: I/O in progress
s: seconds spent for I/O

Get a summary of IO operations.

We use -D option with vmstat to report a summary of disk operations that have been performed by the system.

Display statistics in megabytes.

Display table of event counters and memory statistics.

We use the -s option with vmstat to display a table of event counters and memory statistics.

Display information about kernel objects stored in slab layer cache.

LINUX FUNDAMENTALS | Mangesh Abnave


Using the vmstat command with the -m option displays the names and sizes of various kernel objects stored in
a cache known as the slab layer. Slab info refers to caches of frequently used objects in the kernel, such as
buffer heads, inodes, dentries, and so on. Vmstat displays information about some of these caches.

cache: Cache name


num: Number of currently active objects
total: Total number of available objects
size: Size of each object
pages: Number of pages with at least one active object

Using vmstat, this next command will grep the memory and give a good overview of the memory used in the
computer.

Display number of forks since last boot

This displays all the fork system calls made by the system since the last boot. This displays all fork, vfork, and
clone system call counts.

LINUX FUNDAMENTALS | Mangesh Abnave


Use option -w to increase the width of the output columns as shown below. This give better readability

MORE Command:

Basic usage is very easy. Let's say you are trying to 'cat' a file, and it's too long/large to be displayed on your
screen, then you can use the more command in the following way

You can also combine the more command with other command line tools, something which can be done using
pipes. For example:

Use the -d command line option for this. This will enable more to prompt with "[Press space to continue, 'q' to
quit.]", and display "[Press 'h' for instructions.]" whenever an illegal key is pressed.

If you want, you can even force the more command to squeeze multiple blank lines into one. This can be done
using the -s command line option.
Create file test.txt contain more than one blank lines in between line with help of VI Editor first. Then only you
will get the effect of this command

LINUX FUNDAMENTALS | Mangesh Abnave


By default, more uses the complete screen to display output. However, you can even customize this in terms of
number of lines used by the tool. This can be done by explicitly specifying the number of lines you want more
to use.

For example, if we want more to display the output using 10 lines at a time, then we can do that in the following
way:

You can specify the number of lines to use before the more command stops displaying text

You can get more to start working from a certain line number

Start From A Certain Line Of Text


If you want to skip most of a file until you get to a certain line of text use the following command:

LINUX FUNDAMENTALS | Mangesh Abnave


How to view the contents of multiple files

more /usr/share/dict/*

How to Run Two or More Terminal Commands at Once in Linux

The Semicolon (;) Operator

The Logical AND Operator (&&)

If you want the second command to only run if the first command is successful, separate the commands with
the logical AND operator, which is two ampersands ( && ). For example, we want to make a directory called
MyFolder and then change to that directory–provided it was successfully created. So, we type the following on
the command line and press Enter.

We recommend using the logical AND operator rather than the semicolon operator most of the time (;). This
ensures that you don’t do anything disastrous.

The Logical OR Operator (||)


Sometimes you might want to execute a second command only if the first command does not succeed. To do
this, we use the logical OR operator, or two vertical bars ( || ).

LINUX FUNDAMENTALS | Mangesh Abnave


[ ] Square Bracket Means test command. We are using test command to check the condition.

Combining Multiple Operators

You can combine multiple operators on the command line, too. For example, we want to first check if a file
exists ( [ -f ~/sample.txt ] ). If it does, we print a message to the screen saying so ( echo “File exists.” ). If not,
we create the file ( touch ~/sample.txt ). So, we type the following at the command prompt and press Enter.

[ -f ~/sample.txt ] && echo “File exists.” || touch ~/sample.txt

LESS Command:

Less command is Linux utility which can be used to read contents of text file one page (one screen) per time. It
has faster access because if file is large, it don’t access complete file, but access it page by page. Less is a program
similar to more but which allows backward movement in the file as well as forward movement.

Less command can be used to restrict the output of any other command.

The below command tells less to start at first occurrence of pattern “failure” in the file.

LINUX FUNDAMENTALS | Mangesh Abnave


It will show output along with line numbers

To Starts up the file from the given number(less +number file_path)

You probably already know that you can use tail command to monitor log files in real time.

You can also do the same with less command. You can see the new lines being added to a file in real time by
using the +F option.

To open multiple files with less, simply input the file names one by one:

:n – view the next file in the list


:p – view the previous file in the list

LINUX FUNDAMENTALS | Mangesh Abnave


Marking interesting points

While you are scrolling through a big text file and you find something interesting, but you also need to continue
checking the file, how would you remember that interesting point? Answer is marking.

Less allows you to add marks, sort of flags, to any line. You can add a mark by pressing the key ‘m’ followed by
a letter.

less /var/log/messages

While accessing this file if i pressed m it will show mark prompt at the bottom pressed any letter then by that
letter a flag will be created and with the help same flag i will be able to go back to the same position of the file

ma (i pressed m and maked the flagged by letter a)

Then if i want to go back to the flag "a" then type following command

'a

HEAD Command:

The head command, as the name implies, print the top N number of data of the given input. By default it prints
the first 10 lines of the specified files.

-n num: Prints the first ‘num’ lines instead of first 10 lines. num is mandatory to be specified in command
otherwise it displays an error.

LINUX FUNDAMENTALS | Mangesh Abnave


-c num: Prints the first ‘num’ bytes from the file specified. Newline count as a single character, so if head prints
out a newline, it will count it as a byte. num is mandatory to be specified in command otherwise displays an
error.

-q: It is used if more than 1 file is given. Because of this command, data from each file is not precedes by its file
name.

Without –q option the out of the command will be as follows

With the –q option the output of the file as follows:

LINUX FUNDAMENTALS | Mangesh Abnave


-v: By using this option, data from the specified file is always preceded by its file name.

We can use head and tail command together in order read the data. Now below example show that I want to
print only last 2 line of file so I combined both head and tail command together

LINUX FUNDAMENTALS | Mangesh Abnave


TAIL Command:

Tail is a command which prints the last few number of lines (10 lines by default) of a certain file, then
terminates.

By default “tail” prints the last 10 lines of a file, then exits.

Now what about you are interested in just the last 3 lines of a file, or maybe interested in the last 15 lines of a
file. this is when the -n option comes handy, to choose specific number of lines instead of the default 10.

We can even open multiple files using tail command with out need to execute multiple tail commands to view
multiple files. Suppose if you want to see first two lines of a

Now this might be by far the most useful and commonly used option for tail command. Unlike the default
behavior which is to end after printing certain number of lines, the -f option “which stands for follow” will keep
the stream going. It will start printing extra lines on to console added to the file after it is opened.

LINUX FUNDAMENTALS | Mangesh Abnave


We have other option -s which should always be used with -f” will determine the sleep interval, whereas tail -
f will keep watching the file, the refresh rate is each 1 second, if you wish to control this, then you will have to
use the -s option “sleep” and specify the sleep interval

We can open more files using tail command. Even we can view 2 files at the same time growing using -f option
as well. It will also print a header viewing which file is showing this output. the header line will be beginning
with “==>”

If you want to remove this header, use the -q option for quiet mode.

Now what if I have a very huge for e.g. /root/test.txt and I am only interested in the last certain number of
bytes of data, the -c option can do this easily. Observe the below example where I want to view only the last
10 bytes of data from /root/test.txt

LINUX FUNDAMENTALS | Mangesh Abnave


WATCH Command:

While working on the Linux command line, you might want to execute a command repeatedly so as to track any
change in output.

The basic usage of watch is very easy - all you have to do is to run the tool with a command name as input. For
example:

As already explained in the previous section, the output of the command being tracked is regularly updated
(after 2 seconds by default). In case you want, you can also make 'watch' highlight the part of output that's
changing between updates.

The default update interval is 2 seconds. However, if you want, you can change this value by using the -n
command line option, which requires you to pass the new interval value as its input.

If you want, you can also ask 'watch' to turn off the header showing the interval, command, and current time
at the top of the display, as well as the following blank line. This can be done using the -t command line option.

If you want the 'watch' command to exit after a change in output is detected, use the -g command line option.
How we can try this command do execute this command and open the second terminal and touch the file any
new changes happened in directory watch command will exit out automatically with –g option.

LINUX FUNDAMENTALS | Mangesh Abnave


SORT Command:

Create one file with the content in the file as follows it should be the same case as it is printed

Now sort the content of the file using following command.


Checked the out of both the files carefully. First command is the original file and second command is sort
command. Now sort command only display the data in sorted format the original data will be the same.

If you want the output of the sort command should be permanently stored then you need to do the output
redirection method to store the data as follows

LINUX FUNDAMENTALS | Mangesh Abnave


Now sort the contents of text file ‘mangesh.txt‘ in reverse order by using ‘-r‘ switch and redirect output to a file
‘reversesorted.txt‘. Also check the content listing of the newly created file.

We are going a create a new file (lsl.txt) at the same location for detailed examples and populate it using the
output of ‘ls -l‘ for your home directory.

LINUX FUNDAMENTALS | Mangesh Abnave


Sort the contents of file ‘lsl.txt‘ on the basis of 2nd column (which represents number of symbolic links).

Sort the contents of file ‘lsl.txt‘ on the basis of 9th column (which is the name of the files and folders and is non-
numeric).

It is not always essential to run sort command on a file. We can pipeline it directly on the terminal with actual
command.

Sort and remove duplicates from the text file mangesh.txt. Check if the duplicate has been removed or not

LINUX FUNDAMENTALS | Mangesh Abnave


Sort the contents of two files on standard output in one go.

-M Option : To sort by month pass the -M option to sort. This will write a sorted list to standard output
ordered by month name.

RPM Commands:

How to Check an RPM Signature Package

Always check the PGP signature of packages before installing them on your Linux systems and make sure its
integrity and origin is OK. Use the following command with –checksig (check signature) option to check the
signature of a package called MySQL-client-3.23.57-1.i386.rpm

LINUX FUNDAMENTALS | Mangesh Abnave


How to Install an RPM Package

For installing an rpm software package, use the following command with -i option. For example, to install an
rpm package called rsyslog-mysql-8.24.0-16.el7.x86_64.rpm.rpm

How to check dependencies of RPM Package before Installing

Let’s say you would like to do a dependency check before installing or upgrading a package. For example, use
the following command to check the dependencies of BitTorrent-5.2.2-1-Python2.4.noarch.rpm package. It will
display the list of dependencies of package.

How to Install a RPM Package Without Dependencies


If you know that all needed packages are already installed and RPM is just being stupid, you can ignore those
dependencies by using the option –nodeps (no dependencies check) before installing the package.

How to check an Installed RPM Package


Using -q option with package name, will show whether an rpm installed or not.

LINUX FUNDAMENTALS | Mangesh Abnave


How to List all files of an installed RPM package
To view all the files of an installed rpm packages, use the -ql (query list) with rpm command.

How to List Recently Installed RPM Packages


Use the following rpm command with -qa (query all) option, will list all the recently installed rpm packages.

How to List All Installed RPM Packages


Type the following command to print the all the names of installed packages on your Linux system.

How to Upgrade a RPM Package


If we want to upgrade any RPM package “–U” (upgrade) option will be used. One of the major advantages of
using this option is that it will not only upgrade the latest version of any package, but it will also maintain the
backup of the older package so that in case if the newer upgraded package does not run the previously installed
package can be used again.

LINUX FUNDAMENTALS | Mangesh Abnave


How to Remove a RPM Package:

How to Remove an RPM Package Without Dependencies


The –nodeps (Do not check dependencies) option forcefully remove the rpm package from the system. But keep
in mind removing particular package may break other working applications.

How to Query a file that belongs which RPM Package


Let’s say, you have list of files and you would like to find out which package belongs to these files. For example,
the following command with -qf (query file) option will show you a file /usr/bin/htpasswd is own by package
httpd-tools-2.2.15-15.el6.centos.1.i686.

How to Query a Information of Installed RPM Package


Let’s say you have installed an rpm package and want to know the information about the package. The following
-qi (query info) option will print the available information of the installed package.

LINUX FUNDAMENTALS | Mangesh Abnave


Get the Information of RPM Package Before Installing
You have download a package from the internet and want to know the information of a package before
installing. For example, the following option -qip (query info package) will print the information of a package.

How to Query documentation of Installed RPM Package


To get the list of available documentation of an installed package, use the following command with option -qdf
(query document file) will display the manual pages related to vmstat package.

LINUX FUNDAMENTALS | Mangesh Abnave


How to Verify all RPM Packages
Type the following command to verify all the installed rpm packages.

LINUX FUNDAMENTALS | Mangesh Abnave