Thursday, 23 March 2017
Linux Basics
## Linux Basics ##
     UNIX is the first Operating system in the
world, developed by Kem Thompson and Dennis Ritchie in 1969 at Bell Lab by
AT&T Company
            IBM    :           AIX
            SGI     :           IRIX
            Sun     :           Solaris
            Free
software foundation organization, they start a project by name GNU. The main
aim of this project is to develop such an operating system that can run on any
platform.
    In 1991, a student Linuz Torvalds developed a
kernel named Linux’s kernel plus GNU application called Linux operating system.
Linux is an open source technology.
Different companies that provide Linux in Market are Redhat, SuSe,
Scientific, Centos, and Knoppix etc.
Features:
Ø  Linux is the fastest Operating system in the world. It runs 2 to 3
times fast than windows OS.
Ø  Linux is the much secured OS because there is no any problem of
virus.
Ø  Linux file format is text format and windows file format is binary
format.
Ø  Linux is very reliable OS because kernel of Linux is very stable
as compare to windows kernel not crashed easily.
Ø  Kernel of Linux is very small in size it can be stored in floppy.
Ø  Linux uses the x-Window system which is advanced network windowing
system. Using this system we can display output of any workstation monitor
attached in the network.
Advantages:
Ø  Virus Proof
Ø  Crash Proof
Ø  Economical
Ø  Multiuser, Multi-Tasking and Multi processing capacity
Login Modes:
Two modes:  
1.Text mode (CLI) - All the commands can be executed
2.Graphical Mode (GUI)
1.Text mode (CLI) - All the commands can be executed
2.Graphical Mode (GUI)
Login to Text mode we have use (Ctrl+Alt+F1…..F6,
F8….F12) (Ctrl+Alt+F7) for Graphical Mode
Open Source
       The idea behind Open
Source software is rather simple: when programmers can read, distribute and
change code, the code will mature. People can adapt it, fix it, debug it, and
they can do it at a speed that dwarfs the performance of software developers at
conventional companies. This software will be more flexible and of a better
quality than software that has been developed using the conventional channels,
because more people have tested it in more different conditions than the closed
software developer ever can.
The Open Source initiative started to make this clear to the commercial world, and very slowly, commercial vendors are starting to see the point. While lots of academics and technical people have already been convinced for 20 years now that this is the way to go, commercial vendors needed applications like the Internet to make them realize they can profit from Open Source. Now Linux has grown past the stage where it was almost exclusively an academic system, useful only to a handful of people with a technical background. Now Linux provides more than the operating system: there is an entire infrastructure supporting the chain of effort of creating an operating system, of making and testing programs for it, of bringing everything to the users, of supplying maintenance, updates and support and customizations, etcetera. Today, Linux is ready to accept the challenge of a fast-changing world.
The Open Source initiative started to make this clear to the commercial world, and very slowly, commercial vendors are starting to see the point. While lots of academics and technical people have already been convinced for 20 years now that this is the way to go, commercial vendors needed applications like the Internet to make them realize they can profit from Open Source. Now Linux has grown past the stage where it was almost exclusively an academic system, useful only to a handful of people with a technical background. Now Linux provides more than the operating system: there is an entire infrastructure supporting the chain of effort of creating an operating system, of making and testing programs for it, of bringing everything to the users, of supplying maintenance, updates and support and customizations, etcetera. Today, Linux is ready to accept the challenge of a fast-changing world.
Kernel: It is a program. Kernel
is a Core component of operating system, interacts directly with hardware and
provides low level services to upper layer components.
Shell: An interface to kernel, hiding complexity of kernel’s functions
from users. Takes commands from user and executes kernel’s functions.
User Interface: In information technology, the user interface (UI) is everything
designed into an information device with which a human being may interact. Two
types CLI (Command line interface) and GUI (Graphical User Interface).
System Library - System libraries are special functions or programs using which
application programs or system utilities accesses Kernel's features. These
libraries implements most of the functionality of the operating system and do
not requires kernel module's code access rights.
System Utility - System Utility programs are responsible to do specialized,
individual level tasks.
Kernel Mode vs User Mode
Kernel component code executes in a special privileged mode called kernel mode with full access to all resources of the computer. This code represents a single process, executes in single address space and do not require any context switch and hence is very efficient and fast. Kernel runs each processes and provides system services to processes, provides protected access to hardwares to processes.
Support code which is not required to run in kernel mode is in System Library. User programs and other system programs works in User Mode which has no access to system hardwares and kernel code. User programs/ utilities use System libraries to access Kernel functions to get system's low level tasks.
Basic Features
Following are some of the important features of Linux Operating System.
Portable - Portability means softwares can works on different types of hardwares in same way.Linux kernel and application programs supports their installation on any kind of hardware platform.
Open Source - Linux source code is freely available and it is community based development project. Multiple teams works in collaboration to enhance the capability of Linux operating system and it is continuously evolving.
Multi-User - Linux is a multiuser system means multiple users can access system resources like memory/ ram/ application programs at same time.
Multiprogramming - Linux is a multiprogramming system means multiple applications can run at same time.
Hierarchical File System - Linux provides a standard file structure in which system files/ user files are arranged.
Shell - Linux provides a special interpreter program which can be used to execute commands of the operating system. It can be used to do various types of operations, call application programs etc.
Security - Linux provides user security using authentication features like password protection/ controlled access to specific files/ encryption of data.

Linux System Architecture is consists of following layers
Hardware layer - Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).
Kernel - Core component of Operating System, interacts directly with hardware, provides low level services to upper layer components.
Shell - An interface to kernel, hiding complexity of kernel's functions from users. Takes commands from user and executes kernel's functions.
Utilities - Utility programs giving user most of the functionalities of an operating systems.
Windows Vs Linux
| 
                               
  Windows | 
                                     
  Linux | 
| 
·        
  It is a proprietary software everything need to buy | 
·        
  It is an open source software everything is free | 
| 
·        
  Less Secure | 
·        
  More Secure | 
| 
·        
  More costly | 
·        
  Less Cost compare to windows | 
| 
·        
  Chance to get a carpal tunnel syndrome | 
·        
  There is no chance to get carpal tunnel syndrome | 
| 
·        
  Developed by Microsoft corporation | 
·        
  Developed by Linus Torvalds | 
| 
·        
  Options need to select | 
·        
  You can develop anything as per your requirement | 
| 
·        
  Kernel is not editable | 
·        
  Kernel is editable | 
BASH: Bourne again shell
 when you login to the
Server using any CLI based tool OR login to the CLI mode you can see as like
below screen. 
$ sign = local user/non-privilege user
# sign = Administrator/Privileged user
$ sign = local user/non-privilege user
# sign = Administrator/Privileged user
Shells can be changed based
the user compatibility and requirements, most of default shell is 'BASH'  
Command Line Completion:
Single Tab – it will provide the best option
Double Tab – it will provide all the possible
options (Autocompletes)
Command Line Editing:
Ctrl+a            -           It moves cursor to the Home line
position
Ctrl+b            -           Moves the cursor back one character
Ctrl+c            -           Sends the signal SIGINT to the current
task, which aborts and close it.
Ctrl+d            -           Close current shell prompt
Ctrl+e            -           It will move a cursor to end of the
bash
Ctrl+f             -           Moves cursor forward one character
Ctrl+g            -           Abort the research and restore the
original file
Ctrl+h            -           Deletes the previous character (Same
as backspace)
Ctrl+k            -           It is used to delete the command from
the courser to line home position
Ctrl+l             -           Clear the screen
Ctrl+u            -           Clears the line content before the
cursor and copies it into the clipboard
Ctrl+y            -           Yank the content from the cursor
position
Ctrl+z            -           Sends the signal SIGTSTP to the
current task, which suspend it
Ctrl+Shift+c -           Copy selected text
Ctrl+Shift+v            -           Paste the copied content
Ctrl+Shift+t             -           Tab
Ctrl+Shift+n            -           New Terminal
Ctrl+Shift+w            -           Close Tab
Ctrl+Shfift+q           -           Close a Terminal
Alt+b              -           Moves the cursor backward one word
Alt+c              -           Capitalizes the character under the
cursor and moves to the end of word
Alt+d              -           Cut the word after the cursor
Alt+f               -           Moves the cursor forward one word
Alt+l               -           Lowers the case of every character
from the cursor’s position to the end
Alt+.               -           Insert the last argument to the
previous command
Command Line History: Command
line history will be saved, when you execute any command in terminal.
 
$
history        -           this command will display all the
previous executed commands
$ history –c   -           Clear the command history
$ !<number>
-          it executes mentioned number command
Note: Default history size is 1000 commands
$ !<charectar>         -           it will display/execute matching
character command
$ !!                              -           it will execute last executed command
Sophisticated prompt
control:
?          -           It will replace a single character
Example:       rm –rf
a?        -           it will delete the files with two characters
                        Rm –rf a??     -           it will delete the three characters
files after “a”
*          -           replace multiple number of characters
Example: rm –f a* - it will remove all the files which are starting with “a”
Piping and Redirecting:
Redirecting input and output from
standard stream to user defined place
1.    Input RD       -0                                 <         
2.    Output RD
-1              Values        >          Symbols
3.    Error RD       -2                                 >
Example: $ sort < <file name>
                        $ wc < <file name>
                        $ history > f2
                        $mkdir d1 2> e1
Piping sending output or one command as a input to the another command
| pipe
Page related command:
            Less: is used to see the command output page
by page in up and down way
            More: we can’t go upward downward, just see
the output fit to the screen
 
Linux Directory Structure
Overview
Everything in Linux can be reduced to a
file. Partitions are associated with files such as /dev/hda1. Hardware
components are associated with files such as /dev/modem. The Filesystem Hierarchy
Standard (FHS) is the official way to organize files in Unix and Linux
directories.
Linux file system and directory structure
Several major directories are
associated with all modern Unix/Linux operating systems. These directories
organize user files, drivers, kernels, logs, programs, utilities, and more into
different categories. The standardization of the FHS makes it easier for users
of other Unix-based operating systems to understand the basics of Linux. All of
the other directories shown in Table are subdirectories of the root directory,
unless they are mounted separately.
| 
Directory | 
Description | 
| 
/ | 
The root directory, the top-level directory in the FHS.
  All other directories are subdirectories of root, which is always mounted on
  some partition. All directories that are not mounted on a separate partition
  are included in the root directory’s partition. | 
| 
/bin | 
Essential command line utilities. Should not be mounted
  separately; otherwise, it could be difficult to get to these utilities when
  using a rescue disk. | 
| 
/boot | 
Includes Linux startup files, including the Linux kernel.
  Can be small; 16MB is usually adequate for a typical modular kernel. If you
  use multiple kernels, such as for testing a kernel upgrade, increase the size
  of this partition accordingly. | 
| 
/etc | 
Most basic configuration files. | 
| 
/dev | 
Hardware and software device drivers for everything from
  floppy drives to terminals. Do not mount this directory on a separate
  partition. | 
| 
/home | 
Home directories for almost every user. | 
| 
/lib | 
Program libraries for the kernel and various command line
  utilities. Do not mount this directory on a separate partition. | 
| 
/mnt | 
The mount point for removable media, including floppy
  drives, CD-ROMs, and Zip disks. | 
| 
/opt | 
Applications such as WordPerfect or Star Office. | 
| 
/proc | 
Currently running kernel-related processes, including
  device assignments such as IRQ ports, I/O addresses, and DMA channels. | 
| 
/root | 
The home directory of the root user. | 
| 
/sbin | 
System administration commands. Don't mount this directory
  separately. | 
| 
/tmp | 
Temporary files. By default, Red Hat Linux deletes all
  files in this directory periodically. | 
| 
/usr | 
Small programs accessible to all users. Includes many
  system administration commands and utilities. | 
| 
/var | 
Variable data, including log files and printer spools. | 
Linux Booting
procedure
The stages involved in Linux Booting Process are:
1. BIOS
The stages involved in Linux Booting Process are:
1. BIOS
2. Boot Loader
- MBR
- GRUB
- MBR
- GRUB
3. Kernel
4. Init
5. Runlevel scripts
4. Init
5. Runlevel scripts
6. User Interface
STEP 1. BIOS
- This is the first thing which
     loads once you power on your machine.
- When you press the power button
     of the machine, CPU looks out into ROM for further instruction.
- The ROM contains JUMP function
     in the form of instruction which tells the CPU to bring up the BIOS
- BIOS determine all the list of
     bootable devices available in the system.
- Prompts to select bootable
     device which can be Hard Disk, CD/DVD-ROM, Floppy Drive, USB Flash Memory
     Stick Etc..
- Operating System tries to boot
     from Hard Disk where the MBR contains primary boot loader.
STEP 2. Boot Loader 
To be very brief this
phase includes loading of the boot loader (MBR and GRUB/LILO) into memory to
bring up the kernel.
MBR (Master Boot Record)
MBR (Master Boot Record)
- It is the first sector of the
     Hard Disk with a size of 512 bytes.
- The first 434 - 446 bytes are the primary boot loader, 64 bytes for
     partition table and 6 bytes for
     MBR validation timestamp.
NOTE: Now MBR directly cannot load the kernel
as it is unaware of the file system concept and requires a boot loader with
file system driver for each supported file systems, so that they can be
understood and accessed by the boot loader itself.
To overcome this situation GRUB is used with the details of the file system in /boot/grub.conf and file system drivers
GRUB (Grand Unified Boot loader)
this loads the kernel in 3 stages
GRUB stage 1:
To overcome this situation GRUB is used with the details of the file system in /boot/grub.conf and file system drivers
GRUB (Grand Unified Boot loader)
this loads the kernel in 3 stages
GRUB stage 1:
- The primary boot loader takes
     up less than 512 bytes of disk space in the MBR - too small a space to
     contain the instructions necessary to load a complex operating
     system. 
- Instead the primary boot loader
     performs the function of loading either the stage 1.5 or stage 2 boot
     loader.
GRUB Stage 1.5: 
- Stage 1 can load the stage 2
     directly, but it is normally set up to load the stage 1.5. 
- This can happen when the /boot
     partition is situated beyond the 1024 cylinder head of the hard
     drive. 
- GRUB Stage 1.5 is located in
     the first 30 KB of Hard Disk immediately after MBR and before the first
     partition.
- This space is utilized to store
     file system drivers and modules.
- This enabled stage 1.5 to load
     stage 2 to load from any known location on the file system i.e. /boot/grub
GRUB Stage 2:
- This is responsible for loading
     kernel from /boot/grub/grub.conf and any other modules needed
- Loads a GUI interface i.e.
     splash image located at /grub/splash.xpm.gz with list of available kernels where you can
     manually select the kernel or else after the default timeout value
     the selected kernel will boot
The original file
is /etc/grub.conf of which you can observe a symlink file
at /boot/grub/grub.conf
STEP 3. Kernel
This can be considered
the heart of operating system responsible for handling all system processes.
Kernel is loaded in the following stages:
Kernel is loaded in the following stages:
- Kernel as soon as it is loaded
     configures hardware and memory allocated to the system.
- Next it uncompresses the
     initrd image (compressed using zlib into  zImage or
     bzImage formats) and mounts it and loads all the necessary drivers.
- Loading and unloading of kernel
     modules is done with the help of programs like insmod, and rmmod present
     in the initrd image.
- Looks out for hard disk types
     be it a LVM or RAID.
- Unmounts initrd image and frees up all the memory occupied
     by the disk image.
- Then kernel mounts the root
     partition as specified in grub.conf as read-only.
- Next it runs the init process
STEP 4. Init Process
- Executes the system to boot
     into the run level as specified in /etc/inittab
You can check current runlevel details of your system using below command on the terminal
# who -r
run-level 3 Jan 28 23:29 last=S
- Next as per the fstab entry
     file system's integrity is checked and root partition is
     re-mounted as read-write (earlier it was mounted as read-only).
STEP 5. Runlevel scripts
A no. of runlevel
scripts are defined inside /etc/rc.d/rcx.d
- Based on the selected runlevel,
     the init process then executes startup scripts located in subdirectories
     of the /etc/rc.ddirectory.
- Scripts used for runlevels 0 to
     6 are located in subdirectories /etc/rc.d/rc0.d through /etc/rc.d/rc6.d, respectively.
- For more details on scripts
     inside /etc/rc.d follow the below link
 What are the s and k scripts in the etc rcx.d directories
- Lastly, init runs whatever it
     finds in /etc/rc.d/rc.local (regardless of run level). rc.local is
     rather special in that it is executed every time that you change run
     levels.
NOTE: rc.local is not used in all the distros as for
example Debian.
Next if everything
goes fine you should be able to see the Login Screen on your
system.
Basic and Common commands
           Before you turn
over to the next chapter where you are going to meet a plethora of commands,
remember a few things that apply to all UNIX commands.
-     
     All UNIX commands must always be entered in small case letters
-     
     Between the command name and the options that may be available with the
     command there must always be a space or a tab, for example, ls –l. Here is
     the command whereas –l is the option and the two have been separated by
     space. The option is usually preceded by a minus (-) sign. The option
     available with a command are often known as switches
-       Two or more
     options available with command can usually be combined, for example, the
     command ls –l –a is same as ls –la
-  
          If you make a typing mistake, press
     backspace to erase characters Don’t try back using arrow keys and then
     attempt deleting using the del key
-      To cancel the entire
     command before you press Enter, press ctrl+c Or del key
Basic Commands:
~]$ date             #To see the date
of the system.
~]$ date +%d-%Y-%H-%M  #To see
particular date format you always use date options
~]$ cal #To see the current month calendar.
~]$ cal 11 2014            #To display the
calendar, Month November (11) and year 2014
~]$ clear            #To clear the
screen
~]$ ls –l            #List files,
directories with their properties
~]$ ls                   #To list files
and directories
~]$ ls –a            #To list all
hidden files and directories
~]$ ls –d            #To list only
directories
 ~]$ pwd             #Print working directory
~]$ who am I    #To see from
which user you have logged in
~]$ who             #To see all who
is logged in yet this point of time from which IP
~]$ w                  #More details
about user related info
 ~]$ uptime        #To see the
server up time, boot time, users and load
 ~]$ uname –a     #Verify Operating
system version, kernel version and architecture
~]$ touch <File Name>         #Create an empty
file / Multiple empty files yet a time
Options:
~]$ touch –am                                   #it will change a
file time to current time
~]$ touch –r file1 –B 30 file2  #it will create two files with 30 seconds time
difference
~]$ cat /dev/null > file                       #To empty the
data file
~]$ cat > <File Name>                      #Create an single
file with text
       In above example
two files 'kumar' and 'ravi' where created because we have provided the space
in between 'kumar' and 'ravi' file names.
~]$ rm –rf <File / Directory Name>    #Delete files and
directories forcefully
~]$rmdir <directory>    #Delete
directories only
 ~]$ mkdir <Directory Name> #Create an empty directory / directories
~]$ mkdir –p
<directory/directory/directory> #to create parent directories
 ~]$ cd <Path
of the directory>         #Change directory
 ~]$ cat
<File Name>              #View content of
file
 ~]$ time             #Calculate
response time of the activity / command
 ~]$ hwclock                  #to see detailed
date and time with time zone
~]$ cp <Source path> <Destination
path>  #Copy the files from one path to another path
~]$cp –Rv <source> <destination> #copy directories from source to destination
Options:
-R,
-r,              #copy directories recursively
-v                     #verbose to see progress of copy job
-p                     #preserve
-f                      #forcefully
-I                     #interactive: Ask before overwriting
file
 Copying directory must use –R to copy
directories
 ~]$ mv
<source> <destination>       #Move
files/directories
~]$ mv <old name> <new name>    #Rename the file
and directory
 ~]$ last                          #Check who logged
in and when logged in duration
~]$ arch             #to know
architecture
 ~]$ reboot / init 6                     #Restart server
~]$poweroff / init 0                  #To shut down the
server
~]$ dmesg                                 #Check boot
process logs
 ~]$ nsloookup
<Server Address>    #check dns
resolution
~]$ dig  <server
address>      #check dns
resolution to debug
~]$ tree <directory>               #it will show the
tree of parent directory
~]$ stat <file name>               #detailed
information about file
 ~]$ wc                            #word count,
character count and line count
Options:
-l          #Check line count
-c         #Character Count
-w        #Word Count
 Help
relate commands:
~]$ whatis <Command Name>  #It will display single line description
about command
 ~]$ whereis
<Command Name> #It will provide you path of the command
~]$ man <command>                 #manual page of
the command
~]$ info <command>              #information
about the command
~]$ <command> --help           #it will gives a
command options and there usage
~]$ apropos <keyword>         #to know about
the command use
Linux Basic/Common commands
Command      Description                 
adduser           Add a new
user                    
arch                  Print machine architecture                
awk                 Find and Replace text within file(s)              
bc                    An arbitrary precision calculator
language                 
cal                    Display a
calendar                  
cat                   Concatenate files and print on the standard
output              
chdir                Change working directory                 
chgrp               Change the group ownership of files             
chkconfig        Tool for maintaining the
/etc/rc[0-6].d directory hierarchy               
chmod             Change the access permissions of files
and directories                    
chown             Change the user and group ownership of
files                      
chroot              Change root directory           
cksum              Print CRC checksum and byte
counts                      
clear                 Clear terminal screen             
cmp                 Compare two
files                 
comm              Compare two sorted files line by line           
cp                    Copy one or more files to another
location               
cron                 Daemon to execute scheduled
commands                
crontab            Schedule a command to run at a later
time               
csplit                Split a file into context-determined
pieces               
cut                   Divide a file into several parts                       
date                 Display or change the date &
time               
dc                    Desk
Calculator                    
dd                    Data Dump - Convert and copy a
file                      
df                    Display free disk
space                     
diff                  Display the differences between two
files               
diff3                Show differences among three files             
dir                    Briefly list directory contents           
dircolors          Colour setup for
`ls'              
dirname           Convert a full pathname to just a
path                      
du                    Estimate file space
usage                  
echo                 Display message on
screen                
ed                    A line-oriented text editor
(edlin)                 
egrep               Search file(s) for lines that match an
extended expression               
eject                 Eject
CD-ROM                     
env                  Display, set, or remove environment
variables                     
expand            Convert tabs to
spaces                      
expr                 Evaluate expressions             
factor               Print prime
factors                
false                 Do nothing,
unsuccessfully               
fdformat          Low-level format a floppy
disk                    
fdisk                Partition table manipulator for Linux           
fgrep                Search file(s) for lines that match a
fixed string                   
find                 Search for files that meet a desired
criteria              
fmt                  Reformat paragraph
text                   
fold                 Wrap text to fit a specified
width                
format             Format disks or tapes            
free                  Display memory
usage                      
fsck                 Filesystem consistency check and
repair                  
gawk               Find and Replace text within
file(s)             
grep                 Search file(s) for lines that match a
given pattern                
groups             Print group names a user is in           
gzip                 Compress or decompress named
file(s)                    
head                Output the first part of file(s)           
hostname         Print or set system
name                   
id                     Print user and group
id's                   
info                  Help
info                   
install               Copy files and set attributes              
join                  Join lines on a common field            
kill                   Stop a process from
running             
less                  Display output one screen at a
time              
ln                     Make links between
files                  
locate               Find
files                    
logname           Print current login
name                    
lpc                   Line printer control
program             
lpr                    Off line print             
lprm                 Remove jobs from the print
queue                
ls                      List information about
file(s)             
man                 Help manual              
mkdir               Create new folder(s)             
mkfifo             Make FIFOs (named
pipes)              
mknod             Make block or character special
files            
more                Display output one screen at a
time              
mount              Mount a file system              
mv                   Move or rename files or directories               
nice                  Set the priority of a command or
job            
nl                     Number lines and write
files             
nohup              Run a command immune to hangups            
passwd            Modify a user
password                   
paste                Merge lines of
files               
pathchk           Check file name
portability               
pr                     Convert text files for printing           
printcap           Printer capability
database                
printenv           Print environment
variables              
printf               Format and print data           
ps                     Process status            
pwd                 Print Working Directory                    
quota               Display disk usage and limits           
quotacheck      Scan a file system for disk
usage                  
quotactl           Set disk quotas                       
ram                  ram disk
device                     
rcp                   Copy files between two
machines                
rm                    Remove files             
rmdir               Remove
folder(s)                  
rpm                  Remote Package
Manager                
rsync                Remote file copy (Synchronize file
trees)                  
screen              Terminal window
manager               
sdiff                Merge two files interactively            
sed                   Stream Editor            
select               Accept keyboard
input                     
seq                   Print numeric
sequences                    
shutdown        Shutdown or restart
linux                 
sleep                Delay for a specified
time                 
sort                  Sort text files            
split                 Split a file into fixed-size
pieces                   
su                     Substitute user
identity                     
sum                  Print a checksum for a
file                
symlink            Make a new name for a
file              
sync                 Synchronize data on disk with
memory                   
tac                   Concatenate and write files in
reverse                      
tail                   Output the last part of
files               
tar                    Tape Archiver           
tee                   Redirect output to multiple
files                   
test                  Evaluate a conditional
expression                 
time                 Measure Program Resource
Use                   
touch               Change file
timestamps                     
top                   List processes running on the
system            
traceroute        Trace Route to Host              
tr                      Translate, squeeze, and/or delete
characters             
true                  Do nothing, successfully                   
tsort                 Topological
sort                    
tty                    Print filename of terminal on
stdin               
umount            Unmount a
device                 
uname              Print system information                   
unexpand        Convert spaces to
tabs                      
uniq                 Uniquify files            
units                Convert units from one scale to
another                   
unshar              Unpack shell archive scripts              
useradd           Create new user
account                   
usermod          Modify user account             
users                List users currently logged in            
uuencode         Encode a binary file               
uudecode        Decode a file created by
uuencode              
vdir                  Verbosely list directory contents (`ls
-l -b')               
watch              Execute/display a program
periodically                    
wc                   Print byte, word, and line
counts                  
whereis            Report all known instances of a
command               
which              Locate a program file in the user's
path                    
who                 Print all usernames currently logged
in                     
whoami           Print the current user id and name
(`id -un')             
xargs                Execute utility, passing constructed
argument list(s)           
yes                   Print a string until interrupted           
1.Creating files, Reading files
and Updating file content 
To create file very first command in Linux we use is ‘
cat' lets see how
to create files using cat command[root@ArkIT ~]# cat > firstfile
This is a first file created using cat command
As mentioned in above ‘>’ redirect symbol we have to use along
with cat command to create file with content. Whenever you type cat >
FILENAME hit enter, than it will just show blank screen below the command now
type some data and press CTRL+d first will save and exit.
To read file content below is the command example
[root@ArkIT ~]# cat firstfile
This is a first file created using cat command
[root@ArkIT ~]# cat >> firstfile
Second line of this file
 
[root@ArkIT ~]# cat firstfile
This is a first file created using cat command
Second line of this file
To append the file content ‘>>’ double grater than we have
to use. Type data and press CTRL+d to save.
2. List files and directories
[root@ArkIT ~]# ls
anaconda-ks.cfg Desktop Documents Downloads file firstfile initial-setup-ks.cfg linux Music Pictures Public rhce Templates Videos
long list with detailed information show. ls -l command will show detailed list of files and directories.
[root@ArkIT ~]# ls -l
total 24
-rw-------. 1 root root 1968 Mar 18 02:26 anaconda-ks.cfg
drwxr-xr-x. 2 root root 6 Mar 17 20:59 Desktop
drwxr-xr-x. 2 root root 6 Mar 17 20:59 Documents
drwxr-xr-x. 2 root root 6 Mar 17 20:59 Downloads
-rw-r--r--. 1 root root 1084 Apr 28 08:16 file
list and sort files based on created date
[root@ArkIT ~]# ls -ltr
total 24
-rw-r--r--. 1 root root 2016 Mar 17 20:58 initial-setup-ks.cfg
-rw-------. 1 root root 1968 Mar 18 02:26 anaconda-ks.cfg
-rw-r--r--. 1 root root 1812 Apr 28 05:59 rhce
-rw-r--r--. 1 root root 1227 Apr 28 06:02 linux
-rw-r--r--. 1 root root 1084 Apr 28 08:16 file
-rw-r--r--. 1 root root 72 May 6 22:45 firstfile
ls
-ltr means l = long list, t = time, r = recursively 
3. Let you know current working
directory
To show in which directory your currently working use pwd commnad
[root@ArkIT ~]# pwd
/root
4.  more – file
perusal filter for crt viewing
more
command is used to filter for paging through text one screenful at a time.
[root@ArkIT ~]# cat anaconda-ks.cfg |more
[root@ArkIT ~]# more -d anaconda-ks.cfg
[root@ArkIT ~]# more anaconda-ks.cfg
5. copy files and directories
from source to destination
To copy the files and directories from one location to other
location we have to use cp command
To copy only files use below command. If you use same command for
directories will not work, have to use -r option along with cp command
[root@ArkIT ~]# cp firstfile /opt/
[root@ArkIT ~]# cp Music/ /opt/
cp: omitting directory ‘Music/’ <<< --- if you didn't use -r option this error will come
 
[root@ArkIT ~]# cp -r Music/ /opt/
[root@ArkIT ~]# ls -l /opt/
total 4
-rw-r--r--. 1 root root 72 May 7 07:15 firstfile
drwxr-xr-x. 2 root root 6 May 7 07:17 Music
whenever copying the files & directories we required to
preserve time stamps to preserving the time stamps of files & directories
use option ‘-p’ along with cp command
[root@ArkIT ~]# ls -l
-rw-------. 1 root root 1968 Mar 18 02:26 anaconda-ks.cfg << -- Original file
 
[root@ArkIT ~]# cp -p anaconda-ks.cfg /opt/
[root@ArkIT ~]# ls -l /opt/anaconda-ks.cfg
-rw-------. 1 root root 1968 Mar 18 02:26 /opt/anaconda-ks.cfg <<--- copied file
ls command with 25 examples
6. Delete files and directories
To delete files and directories use rm command
[root@ArkIT ~]# rm file <<-- Delete regular file with confirmation
rm: remove regular file ‘file’? y
[root@ArkIT ~]# rm -f firstfile <<-- Delete Regular file without asking confirmation
[root@ArkIT ~]# rm -rf Public/ <<-- Delete Directory without asking for confirmation
To delete normal file use rm command it will ask you for the
conformation when deleting. If do not want to prompt any confirmation use -f
option. To delete directories use rm -rf .
Note: Be careful whenever your running rm -rf, avoid wildcard * while
running rm command, Go to the same directory and run rm -rf using wildcard *.
7. Moving files and directories
Moving files meaning that changing the location of files from one
to another path. use mv command 
Syntax: mv [source] [destination]
[root@ArkIT opt]# mv Music/ /root/
mv: overwrite ‘/root/Music’? y
8. Creating New Directories
Most of the guys who are not fimilier with Linux also they know
about mkdir command
[root@ArkIT ~]# mkdir /Testing <<-- Creating Directory under /
[root@ArkIT ~]# mkdir test <<-- Creating Directory in current path
 
[root@ArkIT ~]# mkdir -p /Test/Best/Rest/ <<-- Creating Collaborative directories
9. Changing directories
To go from one directory to another directory we have to use cd command
as you see in above screenshot . (dot) represents current
directory. ..(dot dot) represents its parent directory, what is the use of
them..?
whenever we use cd command cd ../../../ which means we are going two directories back from current.
[root@ArkIT ~]# cd /tmp/ <<-- switch directory to /tmp
 
[root@ArkIT /]# cd /var/log/cups/ <<-- Switch to multiple directories yet the same time
[root@ArkIT cups]# cd ../../../ <<-- Going two directories back
 
[root@ArkIT /]# cd -
/var/log/cups <<-- Going to previously changed path
 
[root@ArkIT cups]# cd ~ <<-- Whereever your go back to User HOME directory
[root@ArkIT ~]# pwd
/root
~ (tild) is used to switch back to HOME path
10. Deleting empty directories
We can also make use of rm command but some time we would like to
delete only empty directories (any directory didn’t contain any data) so rmdir
command is very handy whenever we would like to delete empty directories. as a
example we have taken two directories One is having few files in it another one
is empty.
[root@ArkIT ~]# rmdir /test <<-- Directory having few files in it not deleted
rmdir: failed to remove ‘/test’: Directory not empty
[root@ArkIT ~]# rmdir /Testing/ <<-- Directory is empty deleted successfully
11. Print files
To print files from Linux command line we can use lpr command
[root@ArkIT ~]# lpr rhce <<-- Print rhce file to default printer
 
[root@ArkIT ~]# lpr rhce -P PRINTERNAME <<-- Print rhce file to specified printer
 
[root@ArkIT ~]# lpr -#5 rhce <<--- Print only 5 pages out of all pages
12. List who is logged into system
and run-levels
show who logged in to server and which run level is running
currently 
[root@ArkIT ~]# who
root tty1 2016-05-06 22:06
root pts/0 2016-05-07 07:10 (192.168.4.1)
root pts/1 2016-05-07 09:17 (192.168.4.1)
 
[root@ArkIT ~]# who -r
 run-level 3 2016-05-06 22:05
 
[root@ArkIT ~]# who -d
 
[root@ArkIT ~]# who -H
NAME LINE TIME COMMENT
root tty1 2016-05-06 22:06
root pts/0 2016-05-07 07:10 (192.168.4.1)
root pts/1 2016-05-07 09:17 (192.168.4.1)
 
[root@ArkIT ~]# who -a
 system boot 2016-05-06 22:05
 run-level 3 2016-05-06 22:05
root + tty1 2016-05-06 22:06 12:22 1604
root + pts/0 2016-05-07 07:10 02:45 3973 (192.168.4.1)
root + pts/1 2016-05-07 09:17 . 4995 (192.168.4.1)
13. Clear screen 
Typing all the commands on screen and its output in screen will
look like messy to clear all this output and commands typed useclear command
Video Player
00:00
00:05
14. Check disk and partition
spaces
To list partition space and its utilization you have to use df command
[root@ArkIT ~]# df -t xfs
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/mapper/rhel-root 18307072 3113572 15193500 18% /
 
[root@ArkIT ~]# df -i
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/mapper/rhel-root 18317312 109332 18207980 1% /
 
[root@ArkIT ~]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/rhel-root 18G 3.0G 15G 18% /
 
[root@ArkIT ~]# df -m
Filesystem 1M-blocks Used Available Use% Mounted on
/dev/mapper/rhel-root 17878 3041 14838 18% /
df -t <FileSystem> – it will list only the partition which
are formated with specified file system type
df -i – it will show with inode utilization
df -h – human redable format 
df -m – all partition in MB size
15. Searching for files and its
content 
Searching for the content in file without opening the file use
grep command
[root@ArkIT ~]# grep commands linux
all unix commands with examples
linux commands cheat sheet
list of linux commands pdf
in above example we were searching for ‘commands’ string in
‘linux’ file
[root@ArkIT ~]# grep -v commands linux
linux lab exercises
linux practice labs
linux high performance computing
above example will exclude the specified string (it means which
lines does not contain string will be displayed)
For more and more examples see this
16. Check CPU and Memory
utilization
top command is used to checl CPU utilization, memory utilization
and more. 
17. Stream editor command
sed is stream editor to replace the text in file without opening
in text editors, insert lines, delete lines and replace strings
[root@ArkIT ~]# sed -i 's/oldstring/newstring/g' FILENAME
Sed command with 20 practical
examples
http://arkit.co.in/linux/sed-command-20-practical-examples/
18. killing processes when
struck, hang OR not required
To kill the processes when they struck up, Hang state OR some
unwanted processes not required we can kill them
Send an signal using signal id. Signal id 9 means SIGKILL
[root@ArkIT ~]# kill -9 7330
[root@ArkIT ~]# kill -l
 1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
 6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR
31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3
38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7
58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
19. Listing running processes
when we run an command / script which will generate an process
with process ID and CPU will assign an Nice value priority for it.
[root@ArkIT ~]# ps
 PID TTY TIME CMD
 4995 pts/1 00:00:00 bash
 7416 pts/1 00:00:00 ps
 
[root@ArkIT ~]# ps -aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.4 60032 7804 ? Ss 05:30 0:02 /usr/lib/systemd/systemd --switched-root --sy
root 2 0.0 0.0 0 0 ? S 05:30 0:00 [kthreadd]
[root@ArkIT ~]# ps -U root -u root u <<-- list all processes running by ROOT user
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.4 60032 7804 ? Ss 05:30 0:02 /usr/lib/systemd/systemd --switched-root --sy
root 2 0.0 0.0 0 0 ? S 05:30 0:00 [kthreadd]
root 3 0.0 0.0 0 0 ? S 05:30 0:00 [ksoftirqd/0]
20. Changing the files and
directory permissions
This command most of the Linux administrators know, I think
nobody will work as Linux Administrator without knowing this command. The
command is chmod command
[root@ArkIT ~]# ls -l anaconda-ks.cfg
-rw-------. 1 root root 1968 Mar 18 02:26 anaconda-ks.cfg
[root@ArkIT ~]# chmod 760 anaconda-ks.cfg
[root@ArkIT ~]# chmod o+x anaconda-ks.cfg
 
[root@ArkIT ~]# ls -l
-rwxrw---x. 1 root root 1968 Mar 18 02:26 anaconda-ks.cfg
 
[root@ArkIT ~]# chmod g+x anaconda-ks.cfg
 
[root@ArkIT ~]# ls -l anaconda-ks.cfg
-rwxrwx--x. 1 root root 1968 Mar 18 02:26 anaconda-ks.cfg
We can use chmod command along as numeric numbers and alpha 
chmod
command
4 = read
2 = write
1 = execute
u
= rwx — User permissions
g
= rwx — Group permissions
o
= rwx — Other permissions
21. Changing group
ownership for files and directories
Changing ownership of files and directories using chown and chgrp command
chown
USERNAME:GROUPNAME FILENAME
[root@ArkIT ~]# ls -l anaconda-ks.cfg
-rwxrwx--x. 1 root root 1968 Mar 18 02:26 anaconda-ks.cfg
 
[root@ArkIT ~]# chown root:project1 anaconda-ks.cfg
 
[root@ArkIT ~]# ls -l anaconda-ks.cfg
-rwxrwx--x. 1 root project1 1968 Mar 18 02:26 anaconda-ks.cfg
As shown in above example ownership of anaconds-ks.cfg has been
changed to project1 group and user root. 
[root@ArkIT ~]# chgrp u1 anaconda-ks.cfg
 
[root@ArkIT ~]# ls -l anaconda-ks.cfg
-rwxrwx--x. 1 root u1 1968 Mar 18 02:26 anaconda-ks.cfg
22. Creating and extracting
compressed files (zip files)
tar is the command used to create archive and extract archive
files
[root@ArkIT ~]# tar -czvf test.tar.gz *
anaconda-ks.cfg
Desktop/
Documents/
Downloads/
 
tar command options
-c = create
-z = gzip type file
-v = verbose
-f = file
-x = extract
[root@ArkIT ~]# tar -xvf test.tar.gz
23. Connecting to remote host
using secure shell
In regular times we use this command to connect remote Linux based
host. To connect remote host using root user we have to use below command.
[root@ArkIT ~]# ssh root@192.168.4.21
Above comand will not support GUI to connect remote host using GUI
support, we have to use below command
[root@ArkIT ~]# ssh -XY root@192.168.4.21
24. Securely copy the files and
directories to remote host
To copy the files from present host to remote host we have to use scp command
[root@ArkIT ~]# scp anaconda-ks.cfg root@192.168.4.21:/root/Desktop/
25. cheeking system Date and
Time
To check system Date and Time we have to use date command
[root@ArkIT ~]# date
Sat May 7 14:18:32 IST 2016
 
[root@ArkIT ~]# date +%D:%M:%Y
05/07/16:18:2016
That’s it. 25 most commonly used Linux commands  25 most commonly used Linux
commands  25 most commonly used Linux commands  25 most commonly used
Linux commands
Subscribe to:
Post Comments
                      (
                      Atom
                      )
                    




































No comments :
Post a Comment