You are on page 1of 27

LINUX COMMANDS

cd – change directory, for navigation between directory


Ex $cd ~ -> jump to home directory
cd .. -> parent directory
cd ~ -> home directory
cd -> home directory
cd - -> previous directory

ls – listing files and directories


Ex $ls -l -> display long listiong of files and directories
-l –> long listing
-t –> sort by last modified date and time (recent on top)
-R –> recursively display all files and directories
-a –> display with hidden files
-i –> display inode number for files and directories
-r –> sorting in alphabetical order
-f –> disable colors notations
-s –> display size with associated file and directories
-h –> display size in human readable formate (like mb ,gb, tb)
-1 --> display each file and directory in single line
-S --> sort file and directories by size
-d --> display only single directory information not its contents
-F --> classify file and directories by adding single character at the end

date – display time and date


Ex $date +%H:%M%S -> 11:44:54
%S –> seconds
%M –> minutes
%H –> hours
%T –> hh:mm:ss
%D –> mm/dd/yy
%d –> day value
%m –> month value
%y –> yy year value
%Y –> yyyy year value

mkdir – create new directory


Ex $mkdir dirname
-p -> create hirarachy of directory with single command
$mkdir -p dir1/dir2/dir3 (dir3 is child of dir2 & dir2 is child of dir1)

rm – remove files and directories (for directories -r option is required)


Ex $rm filename
-r -> recursively remove all files and dierctories form specified directory
-R –> same as -r option
-i -> interactive deletion ,ask permission for deletion of file/directories (yes/no)
-f -> forcefully delete
-v –> verbose information displayed
cp – copy file and directory
Ex $cp file1 file2 (sourcefile have only one file, destination have only one file)
$cp file1 fie2 file3 dir3 ( copy file1,file2,file3 into dir3 directory)
$cp -r dir1 dir2 ( for copy directory -r compulsory)
-r -> recursively copy all directory with child files and directory to destination)

mv – move or rename file and directory


Ex $mv source desti (if destination exist then rename it otherwise create new destionation)

cat – using we perform file related operations (ie. Display, create, append, copy, merge file)
Ex $cat file or cat < file -> display file content
$cat > file -> create file
$cat >> file -> append file at the end of file (file previous data not deleted)
$cat file1 > file2 -> copy file1 to file2 ( file2 previous data deleted)
$cat file1 file2 file3 > file4 -> copy file1,file2,file3 to file4 (file4 previous data deleted)

head – display default starting 10 lines of file.


Ex $head filename
-n num or -num –> display number of line from file starting.
-c num –> display number of bytes from file starting.

tail – display default ending 10 lines of file


Ex $tail filename
-n num or -num ->display number of line from file ending
-n +num –> display line number to end of file.
-c num –> display number of byte from end of file.

more – view file content page by page. Scroll only forward direction.
Ex $more filename
enter –> to view next line or scroll line by line.
Space bar –> to view next page or scroll page by page.
q –> quit/ exit and control goes to command prompt
-d –> display status to end of line at the time of scrolling

less – view file content page by page. Scroll forward and backward direction.
Ex $less filename
f –> to view next page or scroll page by page in forward direction.
b –> to view previous page or scroll page by page in backward direction.
q –> quit/exit and control goes to command prompt.

ln – create link to the original file(ie. Softlink and hardlink).if make changes in original or
link it will reflect for both.
Ex $ln originalfile linkfile - create hard link, can not create hardlink for directory.
$ln -s originalfile linkfile – create soft link or symlink or symbolic link for file and directory.
-s –> create soft link
hardlink –> same inode number, size, timestamp. Delete original file no effect on link file.
Softlink –> different inode number, size and timestamp. Its pointer to original file. Delete
original file will effect on like file.

wc – wordcount to count lines, words and characters of file.


Ex $wc file1 -> 34 57 223 file1 (lines words characters file1)
-l –> display only number of lines
-w –> display only number of words
-c –> display only number of characters
-L –> display longest line contained number of characters

cmp – it will comapare file byte by byte. Diplay first difference by line and byte number
Ex $cmp file1 file2

comm – using this command we can compare data of two files and result in 3 columns
Ex $comm a.txt b.txt
1st column -> data present in a.txt but not in b.txt
2 column
nd
-> data present in b.txt but not in a.txt
3rd column -> data present in both file a.txt and b.txt
-1 ->display only 1st column
-2 -> display only 2nd column
-3 -> display only 3rd column
-12 -> display 1st and 2nd column

diff – it will show all differences in the file content


Ex $diff file1 file2
-q -> display message when files are different
-s -> display message when files are identical
-y ->display comparison line by line (parallel comparision)

sdiff – used for side by side comparasion


Ex $sdiff file1 file2

sort – sort lines by alphabhetic order. Sorting done from 1st character of line.
Ex $sort filename
-r –> sort in reverse order
-n –> sort lines by numerical value
-u –> display only uniq lines or duplication line display only one time.
-k num –> sort lines by given field or column number

uniq – display unique content in the file(sorted file). First we have to sort the file.
Ex $sort file | uniq
-d –> display only duplicate line
-c –> display number of occurrences of each line
-i –> ignore case while comparing
-u –> display only unique lines ie the lines which are not duplicated

tee – redirect two output i.e first move to file next move as input to next command by pipe.
Ex $ls -l | tee filename | wc

alias – used to make convinient nickname for command or rename the command
Ex $alias longlist=’ls -l’ -> longlist replaced by ls -l at the time of execution
$alias -> list all alias for current terminal

unalias – used to delete the alias


Ex $unalias longlist -> delete longlist alias from terminal

echo- display formated output on standard output.


Ex $echo “current shell - $SHELL” ->display current shell using access specifer $
$echo {1,2,3}:{a,b,c} ->1:a 1:b 1:c 2:a 2:b 2:c 3:a 3:b 3:c
$echo {a..z} -> abcdefghijklmnopqrstuvwxyz

read var->Read one line of data from STDIN and assign it to a variable var.
-s(no echo like hidden password)
-p “enter value-” (display string to get input from user)
-n number (get number of character from user as input)

$pwd –> display present working directory


$view file -> display file in read only mode
$touch file –> create empty file with current time stamp
$nl file -> number each line in file and display on stdout.
$tac file –> its reverse of cat. Display content in reverse order of lines
$rev file –> reverse each line content
$rmdir dir –> remove/delete directory
$cal -> display current month calender
$set var=10 -> create and assign local variable.
$export var=1 -> create globel variable to access in outter shell
$readonly var=10 -> Read one line of data from STDIN and assign it to a variable that can’t be
changed(like static variable).
$unset var -> deallocate variable from memory.
$clear -> clear the terminal window
$help cmd -> display the list of command & command related brief infromation.
$man cmd -> display mannual information of command in detail which is installed in system.
$sleep sec -> no operation done for specified number of seconds.
$env -> display all enviromental variable (define all in capital latters) & its value.
$time cmd -> command executed and at the last it will display command execution time.
$arch -> display processor architecture and 32/64 bit processor.
$history -> Display the command history used by current user.
$exit -> exit from the current session(logout or ctrl+d key)
$logout -> logout from the current user

tar - tap archive, perform archive,unarchive,compression and uncompression operations


Ex tar -cvf demo.tar file1 file2 file3 -> create tar file (like zip file in windows)
-c –> create archive file
-t –> display archive file content
-x –> extract archive file content
-v -> display verbose information
-z –> compress by using gzip compression technice
-j –> compress by using bzip compression technice
-f –> creates archive with given filename

pr – create printing formate on terminal


Ex $pr file -> display printing formate of file on standard output
-n -> file divided into number of columns
-h -> display header information
-d -> provide double line space
-o n -> margin n space to line starting

lp/lpr – print formated file on printer


Ex $lp file -> print file on priter
-n num -> print number of copy
-printer_name -> print file on specified printer

tr – translate character by character


Ex $tr ‘aeiou’ ‘AEIOU’ < file -> convert vowels small case to capital
-d char –> delete all occurance of character
-s char –> replace squence of all char to single char

locate – search files and directories from database.


Ex $locate filename
-i –> ignore case
-S –> display file and directory number and size

updatedb – update the database of filesystem. By default database updated once in day.
Ex #updatedb

find – search file and directories from filesystem and display full path.
Ex $find . filename -> find filname in current directory
-name “string” –> search files by name
-iname “string”–> search file by name ignore case
-type f –> search file by type (f-file,d-directory,s-socket,b-block special,l-link)
-inum num -> search by inode number
-links num –> search by number of link to file
-maxdepth num–> upto maximum directory level wise searching from binary tree level structure
-mindepth num –> minumum directory level wise searching from binary tree level structure
-size num –> search by exact size, -num less than size , +num greater than size
-empty -> search empty file and directories
-exec ->perform operation on output files and directories
-ok –> prompt to perform operation on output files and directories (yes/no confirmation)
-user username–> search user related files and directories
-group group name –> search group related files and directories
-perm 737 –> search by file permission attribute
-atime 4 –> access time, read the file content with in 4 hours
-ctime 6 –> change time, modify the file or it attributes with in 6 hours
-mtime 2 –> modify time, modify the content with in 2 hours

cut – to extract data from file which contain data in tabular formate
Ex $cut -c 3 file -> extract 3rd character from each line
-c num –>extract number of coloumn character ( , -for saperate number) (n-m for range for number)
-f num –> extract number of field from file (-d char - for define delimeter between field)
grep – globally search a regular expression and print it, global regular expression print. Search
pattern in file and print it on standart output.
Ex $grep ‘pattern’ filename
-e –> search by multiple pattern
-i –> ignore case
-b –> byte offset or byte position dispaly
-f –> file contain pattern for searching string
-c –> display number of occurrences
-H –> filename and matching line are displayed
-o –> display only pattern
-q –> supresses the output
-s –> supresses the error like file not exist
-n –> display line number before results
-l –> display file name which file contain searching pattern
-v –> display non matched lines (invert output)
-w –> display exact pattern matched lines
-A num – display matched line and number of lines after that
-B num – display matched line and number of lines before that
-C num – display matched line and number of lines after and before that (C is optional i.e -num)
-R –> recursive search for directory files
--include –> search only included files
--exclude –> search only in non included files
-E –> normal grep work as egrep
-P –> normal grep work as perl style grep

egrep – extended grep it allow all regular expressions which are not work in grep.
Ex $egrep options “string” filename
all options same as grep command

fgrep – fast grep have less number of options for searching pattern fast.
Ex $fgrep options “pattern” filename
supported options (b,c,e,f,h,i,l,n,v). options working same as grep options

sed-stream editor used to perform all operations(search,modify,delete,insert text) of file


line by line without openning it.
Ex $sed -n ‘2p’ emp.txt -> print 2nd line on stdout from emp.txt file
‘$p’ -> print end line
‘2,4p’ -> print 2nd to 4th line(, as range)
‘2!p’ -> print all line except 2nd line (!invert output)
‘2p;6p’ -> print 2nd and 5th line(; as pattern seperator)
PATTERN COMMANDS LIST
p-print, d-delete,c-replace,e-execute cmd,i-insert line above,r-read file,w-write to file,s-substitution,
-e -> for execute multiple pattern
-i -> save update in file without openning
-n -> remove default printing file data

awk – search file line by line and print in formatted structure on standard output.
Syn- $awk ‘BEGIN{heading operations}{execute for each line}END{end operations}’ filename
Ex $awk -F “:” ‘begin{c=0;}NR>=5 && NR<10{c=c+1; print c”-”$1 $NF;}
end{if(c>100){print “heavy data”}}’ file
$0 - all fields from each line
$1 - first field from each line
$NF - last filed from each line
NF - number of fields from each line
NR - row number (perform operations conditionaly on line number)
FS - field seperator
RS - record seperator
-F - field seperator to seperate each field by defined character.
-f file - define pattern in specified file & call that file using -f option

ADMINISTRATIVE COMMANDS
$hostnamectl –> display detailed information and control the system hostname
$chsh csh ->Change the specified user account’s default shell to csh.
$lsblk -> list block special files with detail infromation
$lsof -> list all open files
$lspci -> list all pci device related information
$lsusb -> list all usb device related information
$lsmod -> list all modules related information
$lshw -> list all hardware related information
$lscpu -> list cpu related detailed information

uname -> disyplay system information


-v -kernal version
-r - kernal release
-a - display all system information

hostname - display system name


Ex $hostname -I - display system ip address
-i -> display ip address and mac address
-v -> display version number
newname –> change newname as system name

chage – user to view and change user password expiry information.


Syntax #chage option user
-l -> list user aging information
-d 2020-12-04 -> set last password change date
-E date -> set the expiry date
-M days -> set maximum no of days to change password
-m days -> set minimum no of days to change password
-I days -> set account inactive days after its expiry
-W days -> give warning before account expiry

passwd – change the user account password


sysntax #passwd username -> change specified user password
passwd -> change current user password
-d -> delete user password make account password less
-e -> immediately expire password & force to change password on next login
-i days -> inactive password after specifed days
-S -> show the password status
-l -> lock the password
-u -> unlock the password

chmod – used to change the permission of file and directory


Ex $chmod 775 file -> user – rwx group -rwx other – r-w permission assign for file
file [read – view file content] [write-modify file content] [execute-run or execute file]
directory [read-list dir content] [write-create & delete file/dir] [execute-enter into dir]
PERMISSION NOTATIONS IN SYMBOLIC
owner notations -> u-user , g-group , o-other , a – all user
permission notations -> r-read , w-write , x – execute , - - nopermission
operator notations -> = assign , - remove , + add
permission notations in numeric mode using octal number (binary octal symbol)
000 0 ---|001 1 --x|010 2 -w-|011 3 -wx|100 4 r--|101 5 r-w|110 6 rw-|111 7 rwx

umask – by using this we can find and assign default permissions for file and directory
Ex $umask -> display 4 digit default permission in encoded formate (ie 0002)
1st digit – special permission indication
2nd digit – permission for user
3rd digit – permission for group
4th digit – permission for other
default file permission -> 666-002=664(rw-rw-r--)
default directory permission -> 777-002=775(rwxrwxr-x)
Ex $umask 0022 -> assign default permission
assign default file permission -> 666-022=644(rw-r--r--)
assign default directory permission -> 777-022=755(rwxr-xr-x)

crontab- used to schedule jobs for execution of script at scheduled time


Ex 00 07 31 12 * /home/om/script.sh -> execute script file every dec 31 at morning 07:00AM
* * * * * -> 1-minute, 2- hours, 3- day of month, 4-month, 5-day of week
@daily /home/om/script ->execute daily midnight 12:00am
@hourly,@weekly,@annually,@monthly,@yearly,@reboot.
, -> field seperater (* 4,8 * * * * script -> execute every 4:00am & 8:00am)
- -> specify range (* 4-8 * * * * script -> execute every hour from 4 – 8 am)
*/4 -> interval time(0,4,8,12,..)
$crontab -l -> list out all scheduled jobs
$crontab -e -> edit or create new scheduling job
$crontab -r -> remove scheduled job from system
$crontab -i -> prompt to user at the time execution(yes/no)
$crontab -u ->execute other user script

nohup-nohang up keep processes running even after exiting the shell or terminal.
Nohup.out file created to save stdout and stderr of command execution.
Ex #nohup bash script.sh -> execute script.sh file in foreground

trap – execute command when defined signals event(interrupt) generated.


Ex #trap command signal -> command is executed when signal generated.
-l ->display signal list with there number
-p ->display signal commands

apt- advanced package tool for ubuntu.used to install,remove,update packages from online.
Ex #apt-get install net-tools ->install net-tools package from online
install - install package
update - update package
remove- uninstall package
purge - uninstall package and config files
search - searching package
show - show package related inforamtion

service-service manager to perform service related operations running in background.


Syntax #service service_name command options
Ex #service mysql start -> start mysql service
start ->start service
stop ->stop service
restart -> restart service
status -> display service status

systemctl-service manager to perform service related operations running in background.


Syntax #systemctl command options service_name
Ex #systemctl start mysql -> start mysql service
start ->start service
stop ->stop service
restart -> restart service
status -> display service status

MEMORY AND PROCESS RELATED COMMANDS

top – monitor live process status and memory usage(ie,cpu,mem,load average) in detail.
Ex $top
PID – process ID
USER – username executing the process
PR – priority value of process execution (20 high and -20 low priority)
NI – nice value of process (-20 high and 20 low priority)
VIRT – virtual memory used by process
RES – physical memory used by process
SHR – shared memory used by process
S - process state( R-running,S-sleeping,T-stopped,Z-zombie,D-uninterruptable sleep,I-idle)

$htop(htop util) ->work same as top, but output display in GUI style.
$vmstat -> display the memory(procs,memory,swap,io,system,cpu) related statistical information.
$free -> display the memory(memory,swap) related statistical information.
$stat file -> display the file(or directory) related statistical(detailed) information.
$df -> file system disk usage display harddisk space details used by file system
$du file -> disk usage display size of file(or directory) used in harddisk.

ps- process status display process related all information.


Ex $ps -> display current user executed command related all processes information
-u user -> defined user related all information
-e -> everything related to process status
-f -> display full attributes
-p PID -> find process by there pid
pidof- display the process id of running process in background
Ex $pidof ls - >8854 (display pid of ls command process running in background)

nice->we can assign the priority for the process at the time of command execution.
Ex #nice -10 ls -> execute ls command on -10 priority(low 20 and high -20 priority)

renice->we can change the priority for the process which is curruntly runnign in background.
Ex #renice -20 8854 -> 8854(PID) process (running in background) priority change to -20 priority

$disown PID ->Remove the specified PID process job from the jobs table for the process.
disown %1 -> remove the 1st job from the jobs table for the process.
$bg 1 ->Resume stopped 1st job in background mode. (stop running process by using ctrl+z key)
$fg 1 ->Resume a 1st job in foreground mode from background mode.
$jobs -> List the active jobs.
#kill -9 PID -> kill PID process (running in background) forcefully(-9 for forcefully kill).

USER ACCOUNT RELATED COMMANDS


#user tab tab -> list all users in system
#compgen -u -> list all users in system
#cat /etc/passwod -> list all users and there information
$group tab tab -> list all groups in system
$groups -> list all active groups in system
#cat /etc/groups -> list all groups and there information
#sudo -i -> jump to root user
#su username -> jump to specified user
#useradd username -> create new user with default groupname as username
#groupadd groupname-> create new group
#newgrp groupname -> assign default group for each file and directory creation
#chown username file -> change file owner to defined user
#chgrp groupname file-> change file group to defined group
#deluser username -> delete user
#userdel -r username -> delete user
#delgroup groupname -> delete group

usermod – modify specified user properties.


Syntax #usermod options username
-c “str” -> add comment to user
-d path -> change home directory of user
-e date -> change expiry date of a user
-g grp_name -> change group for user
-l name -> change user login name
-L -> lock a user
-U -> unlock a user
-p password -> set unencrypted password for user
-s shell -> create a shell for the user
-u uid -> change user id for user

groupmod – change or modify group related properties


syntax #groupmod options groupname
-g GID -> change group id for group
-n name -> change group name
-p password -> assign encrypted password

last – list all users logged in and out recently


Ex $last ->display last login and logout users
-num -> display number of users
-R -> hide host name field
-F -> display login and logout time and date
-w -> display full user and domain name

$finger ->Display information about user accounts on the Linux system or a remote system.
$w -> display login users and there status
$who -> display login user name terminal and time
$whoami -> display login user name only

NET WORKING COMMANDS


ifconfig – display and change available nw interfaces configurations.
Ex $ifconfig – display all active nw interfaces
-a -> display all active and deactive nw interfaces
-s -> display short information
lo up -> active the lo network interface (lo is network interface name)
lo down -> deactivate the lo network interface
arp -> enable arp (-arp disable) on network interfaces
promisc –> enable promiscuous mode(-promisc disable)
allmulti –> enable allmulti attribute (-allmulti disable)
mtu num -> modify maximum transfer unit
lo Ipaddr –> assign ip address to lo nw interface
lo netmask Ipadd –> assign netmask to lo nw interface
lo broadcast ipadd –> assign broadcast to lo nw interface
lo hw ether AA:BB:CC:DD:EE:FF –> change mac address

iwconfig- display and change available wireless nw interface configurations.


Ex $iwconfig – display all wireless nw interfaces
essid “name” -> set network name
nwid on/off -> enable/disable network
nickname “name” –> set the nickname
mode managed –> set operating mode to managed(Ad-hoc,Master,Repeater,Secondary,monitor)
freq 2.46000000-> set operating frequency
rate 11M -> set bitrate
retry 10 -> max no of retry to transmission
ap 00:60:11:AB:66:23: -> set access point
txpower 15 -> set transmission power

Iftop(libpcap0.8-dev util) - live nw bandwidth monitoring tool


Ex #iftop -i wlp2s0 – display live bandwidth of wlp2s0 nw interface

arp – Address resolution protocol manipulate system arp cache. resolve ip to mac address
Ex $arp - display current arp table information
-a -> display all arp information
-v -> display verbos information
-n -> display numarical information
-H ether -> all ethre hardware related information
-s IPADD MACADD -> add static entry which is available in network
-i lo -> delete entry from arp table
-d IPADD -> delete entry from arp table

ping - used check network connectivity , handshaking using ICMP protocol


Ex $ping google.com - handshaking to google.com domain
-c no -> no of packets to send
-s no -> define packet size
-i sec -> change time intervel to send packet
-f -> send data as soon as posible

route - display kernal routing table infromation


$route -n -> display numarical info
$route add default gw IPADD -> add default gateway
$route -C -> display routing cache information
$route del default -> delete default gatway

traceroute – display all routes(hops) that a packet takes to reach destination


Ex $traceroute google.com - display all hops to reach google.com
-m num -> maximum number of hops(default 30)
domain num -> set packet lenght (default is 60)
-4 -> ip address version 4 display
-6 -> ip address version 6 display
-g IP -> packets going throw defined gateway
-p port -> define port address of destination to receive packets
-q num -> define no of probs per hop (default 3)

tracepath - display all routes(hops) that a packet takes to reach destination


Ex $tracepath google.com - display all hops to reach google.com
-n -> display numerical information
-b -> display ip address and hostname
-l num -> set initial packet lenght
-m num -> set maximum number hops
-p port -> define port address of destination to receive packets

tcpdump – used to capture, filter,analyse network and tcp/ip packet sniffing


Ex #tcpdump -i wlp2s0 - analyse wlp2s0 network interface
-c num ->number of packets send to analyse network
-A -> captured packets in ASCII formate
-D -> display all available interfaces
-XX -> captured packets in HEX and ASCII formate
-w file.pcap -> write output to file.pcap
-r file.pcap -> read packets from file
-n -> capture packets with ip address(IPv6)
mtr(mtr util) - (ping + traceroute ) monitoring and diagnostic tool
Ex $mtr google.com
$mtr -m hops -> maximum number of hops
$mtr -s size -> define packet size
$mtr -n -> display numaric value
$mtr -b -> display domain name & IP address
$mtr -c no -> send number of packets to destination
$mtr -r -> read from online write to stdout(terminal)
$mtr -w -> write on stdout read from file
$mtr -i sec -> define interval time to send packet
$mtr --tcp -> tcp syn packtes instade of ICMP packets
$mtr --udp -> udp syn packets instade of ICMP packets

ip(net-tools util) – display and modify data related to network interface, routing, ARP & link
Ex $ip address -> nw interface information (network layer)
$ip addr show lo -> lo interface information
$ip a add IPADD dev lo -> add lo ip address
$ip a del IPADD dev lo -> delete lo ip address
$ip -s addr show lo -> lo statistical information
$ip link -> nw interface information (datalink layer)
$ip link set lo up -> enable nw interface
$ip link set lo down -> disable nw interface
$ip route -> routing related information
$ip neighbour -> neighbour devices and its state (arp)
$ip neighbour add IPADD dev lo -> add arp entry in table
$ip neighbour del IPADD dev lo -> delete arp entry from table
STABLE - valid, but unrechable
RECHABLE - valid & rechable
DELAY - packet send but wait for conformation
PERMANENT- ever listing entry that only admin can remove
$ip monitor -> contine monitor and display the state of device

wget(wget util) - download files from web (http,https,ftp,ftps)


Ex $wget url - download from url
$wget -b -> download in background
$wget url -o log -> write log info to file
$wget url -a log -> append log info to file
$wget -c url -> resume download
$wget --tries=3 -> no of times to attemp download
$wget -i file -> url specified in file
$wget -w sec -> wait for tries to connect server
$wget -O file -> replace file name after download
$wget -r url -> recurssively download all files to view offline

curl(curl) -download files from web (http,ftp,imap,pops,scp,sftp,smtp,tftp,telnet,idop,file)


Ex $curl -o file url - download and save as file
$curl -O url -> download and save as original file name
$curl -C url -> resume download
$curl -u username:password url -> authentication to download
$curl -u username:password -T file url -> authentication to upload file
$curl url > xyz.html --libcurl code.c –> c program in code.c

netstat(net-tools)-display information about network connetions, routing tables, nw interface


Ex $netstat -a - show all listening and listening sockets
$netstat -at -> show all tcp ports
$netstat -ut -> show all udp ports
$netstat -l -> show all listining ports
$netstat -x -> list all unix ports
$netstat -s -> list statistics for all ports
$netstat -p > show process id of port
$netstat -c -> show socket information continuously
$netstat -r -> display kernel routing information
$netstat -nr -> display kernel routing information in numarical form
$netstat -i -> display network interfaces
$netstat -ie -> display extended network interfaces
$netstat -g -> display multicast group membership information for ipv4 and ipv6

ss-socket statistics used to display network socket related information or status. replacement
of netstat for speed and better filtering options
Ex $ss - lists all the connections with there state
$ss -l -> lists all listening ports
$ss -a -> listing listening and non listening ports
$ss -t -> listing tcp connections only
$ss -lt -> listing all listening tcp connections
$ss -ua -> listing all udp connections
$ss -ul -> listing all listening udp connections
$ss -p -> display pid of sockets
$ss -s -> display statistical infromation
$ss -4 -> display ipv4 socket connections
$ss -6 -> display ipv6 socket connections
$ss -at '( dport = :22 or sport = :22 )' -sort by source and destination port
$ss -at '( dport = :ssh or sport = : ssh)' - sort by sorce and destination port
$ss -x -> list unix sockets
$ss src IPADD -> perticular source socket information by IPADD
$ss dst IPADD -> perticular destination socket information by IPADD
netid -type of socket
state -established,unconnected,listening
recv-Q - no of received packets in queue
send-Q - no of send packets in queue
local address:port -address of local machine and port
peer address:port - address of remote machine and port

nslookup(dnsutils)-name server lookup used to getting information from the dns server
Ex $nslookup domainname - display 'A record'(IP address) of domain
$nslookup IPADD -> display domain name
$nslookup -type=a -> display record type a related information
A(ip address) SOA(start of authority) NS(name server) MX(mail exchange) txt(text record)
$nslookup -debug domain -> enable debug mode
dig(dnsutils)-domain information groper is used to gather domain related information from
dns server
Ex $dig -v - display dig version
$dig domain -> display domain related information
$dig domain +short -> display only ip address
$dig domain +noall -> display no one any session
$dig domain +nocomments -> ignore comment section
$dig domain +noall +answer -> display only answer section
$dig domain +nostats -> ignore stats section
$dig -f file -> file contain the domain name list
$dig domain MX -> display mx records
first line - version of dig
header - information it received from the server
opt pseudosection - display advanced data , EDNS(extension version) ,udp packet size
question - domain name, IN(internet) , A(address record)
Answer - servername , time to live, IN(internet) class of query, A(address record)
query time- responce time
server - ip address and port responding dns server
when - timestamp when command was run
msg size rcvd - the size of the reply from the dns server

host- used for getting domain related information from dns server
Ex $host domain – display A record (ie ip address)
$host IPADD -> display domain name
$host -v domain -> display verbos output
$host -t ns domain -> specified type of query
$host -C domain -> comapaire the soa records on nameservers
$host -R 3 domain -> no of retries to connect domain
$host -W sec domain -> wait for reply form server
$host -4 domain -> check whether domain uses IPv4 or not
$host -6 domain - check whether domain uses IPv6 or not

ftp(vsftpd) –port-21 file transfer protocol used to upload and download files from remote server.
Ex #apt-get install vsftpd ->install ftp in system
write_enable=YES -> remove comment from this line in /etc/vsftpd.conf file to upload in server
command –>execute command in the server
!command –> execute command in client( current system)
ftp>open Ipadd -> connect to remote system by there ip address (enter password to access)
ftp>ls –> list all file and directory from server
ftp>get file -> download file from server
ftp>mget file1 file2 -> download multiple file from server
ftp>mget * -> download all file from current directory in server
ftp>put file -> upload file to server
ftp>mput file1 file2 -> upload multiple file to server
ftp>? -> list all ftp command
ftp>bye -> to quit from ftp

telnet(telnetd) - port-23 teletype network protocol. access the remote system. non secure
protocol, unencrypted form of data(plain txt), work on tcp/ip nw protocol
Ex $telnet ip -> connect to remote system by ip address
$service inetd status -> check telnet status running or not
$telnet hostname -> connect to remote system by hostname
$telnet user@hostname –> connct ot remote system and login to remote user
$telnet user@hostname port_no –> define destination host port number to access data through port.
$telnet user@ip port_no -> define destination host port number to access data through port.
-4 -> connect with IPv4
-6 -> connect with IPv6
-l username -> login with user

ssh (secure shell/ secure socket shell) port22 (openssh-client,openssh-server util)


transfer data in encrypted form. ssh run at tcp/ip protocol.
Ex #service ssh status ->check running status of ssh
$ssh-keygen ->generate private(hidden) & public key to host connection
established by ssh key.
$ssh-keygen -t rsa ->public key generate on host machine
$ssh hostname ->connecting to server
$ssh username@hostname ->connecting to server
$ssh username@IPADD ->connecting to server
$ssh IPADD ->connecting to server
$ssh username@hostname:port ->connecting to server
$ssh-copy-id hostname ->copy public key to server(no password everytime)
$ssh hostname command ->executing commands on server
(ls, cp, pwd, cd, cat, rm, clear, mv, touch, mkdir)
3 MAJOR ENCRYPTION TECHNIQES USED BY SSH
1>symmetrical -> single public key generation & distributed to client/server
2>Asymmetrical -> 2 key, public(send to host), private kept secure to client
3>hashing -> hash function for generate hash code from data. it's impossible to
regenerate data from hash value. ensure data is unaltered & genuine sender.
-1 -> support ssh version 1
-2 -> support ssh version 2
-4 -> allows only IPv4
-6 -> allows only IPv6
-C -> compress all data(data, stdin,stdout,stderr)
-c cipher_spec -> specify cipher algorithem(encryption) for data transmittion
-n -> prevents reading from stdin
-p port -> destination port number define
-q -> suppresses all errors/warnings
-V -> version number information
-v -> command sysntax information
-E log -> append debug to log file
-g -> connect to local forwarded port (server port)
-i identity_file -> read private key for public key authentication from file
-l user-name ->login to user at host
-w -> wait forever for host reply
-W sec -> how long to wait for reply

telnet ssh
1>access virtual terminal login to server and run command
2>less secure more secure
3>telnet port 23 ssh port 22
4>data in plain text encrypted data
5>sutaible for private nw sutaible for public nw
6>required low bandwidth required high bandwidth
7>used in linux & windows used in all operating system

#scp file user@host:/home/user/destination -> copy to destication host location


$whois google.com –> display google domain information (registration information)
#ifup -> active nw interfaces
#ifdown -> deactivate nw interfaces
#ifplugstatus(ifplugd util) –> check the physical network connection return connection status.

VI EDITOR
cmd/regular mode- we can perform cut copy paste and cursor moving operations in this mode.
insertion/edit mode-we can insert or edit text in this mode.
Execute/replacement mode-we can perform save,quit,search and multiple file switching operations.
-R -> open file in read only mode
+n -> open and move cursor to n line number.
command / regular mode shortcut keys
>>insert into edit/insertion mode
i -> inserts text before current cursor location
I -> insert text beginning of current line
a -> insert text after current cursor location
A -> insert text ending of current line
o -> create a new line for text entry below cursor location
O -> create a new line for text entry above cursor location
cc -> delete current line content only and blank line remains.
cw -> change current word
r -> replace single character under the cursor
R -> replace text from the cursor to right
S -> replace entire line
>>Curosr moving operations
l / right arrow -> cursor move one character right
h / left arrow -> cursor move one character left
j / down arrow -> cursor move down by one line
k / up arrow -> cursor move up by one line
num l -> cursor move number of character right
num h -> cursor move number of character left
num j -> cursor move number of line down
num k -> cursor move number of line up
0/^ -> cursor move beginning of line
$ -> cursor move end of line
- -> cursor move beginning of previous line
+ -> cursor move beginning of next line
w/W -> cursor move to next word
b/B -> cursor move to back word
( -> cursor move to beginning of next sentence
) -> cursor move to beginning of previous sentence
H -> cursor move to top of file
M -> cursor move to middle of screen
L -> cursor move to bottom of screen
ctrl+f /pagedown-> scroll one page down
ctrl +d -> scroll one half screen
ctrl+b/pageup -> scroll one page up
ctrl+u -> move backward half screen
ctrl+e -> move screen up one line
ctrl+y -> move screen down one line
G -> cursor move to last line of file
num G -> cursor move to number of line
>>text deleting / cut operation
x -> cut current character
X -> cut character before the cursor position
num x -> cut number of characters from current character
dd -> cut current line
num dd -> cut number of line from current character
dw -> cut cursor position to beginning of next word
d$ / D -> cut cursor position to end of line
d^ / d0 -> cut cursor position to starting of line
dG -> cut cursor position to end of file
d num G -> cut cursor position to the next number of line
>>yanking /copy text operation
yy -> copy current line
num yy -> copy current line to next number of lines
yw -> copy current position to next starting word
y$ -> copy current position to end of line
y0 / y^ -> ZZcopy current position to starting of line
yG -> copy current position to end of file
y num G -> copy current position to next number of lines
>>other operations
p -> paste the text after the cursor
P
-> paste the text befor the cursor
u -> undo one step
U -> undo entire line changes
~ -> change character case
num u -> undo number of steps
J -> jone two lines one by one
f character -> move cursor to next occured character
/string -> search string at forward direction from cursor position
?string -> search string at backward direction from cursor position
n and N continue search in forward and backward direction
execute/replacement mode shortcuts starting with :
:q -> quit from file
:q! -> quit forcefuly
:w -> save file
:w file -> save as file
:r file -> read data from file
:num -> cursor move to line number
:n -> switching to next file in vi editor
:N -> switching to previous file in vi editor
:buffers -> view no of files open in vi editor
:buffer num -> switching to number of file in vi editor
:! cmd -> execute linux command
:set nu -> set line number
:set nonu -> unset line number
:/word -> search word in file (press n for search next word)
:%s/word -> delete word in file
:%s/word/new/g -> replace word by new string in file globally
% -> means starting of file
:= -> print total number of lines from current line
shift+zz -> save and exit from vi editor

LINUX OTHER CONCEPTS


file types - normal file, directory file, device file

terminal shortcuts
ctrl + alt + t - open terminal
ctrl + d - close terminal
ctrl + z – stop current command or process and give command prompt

character represents the type of file


d - directory
- - normal file
l - link file
c - character special file
b - block special file
s - socket file

directory shortcut notations


. - current directory
.. - parent directory
~ - home directory
/ - root directory
- - previous directory

Absolute path- start from root directory ie /


relative path - start from current directory ./

linux allow same 2 filename in one directory ( ie file, File, filE treated as different)
root user have uid is 0
process id is start from 0 to 65535
child process may not change the environments of the parent process
run script by using $./filename.sh or $sh filename.sh or $bash filename.sh
By default IFS(internal field separater) is space
$echo $0 ->print the current shell ie bash
$? -> return last executed command status
/etc/init.d/mysql start -> running mysql at boot time
cat /etc/protocols -> display complete protocols list
cat /etc/services -> display complete ports list
$cat /etc/shells-> list all available shells in system
redirection and file descriptor
< or 0< - standerd input redirectional operator associated with keyboard
> or 1> or 2> - standerd output(1) and error(2) redirectional operator associated with terminal
file descriptor(0,1,2) - 0-stdinput 1-stdoutput 2-stderror

| - pipe symbol for redirect output of previous command is input for the next command.

wild character used for subtitution of pattern ie name of file directory or string
* - zero or more characters
? - represent only one any character
[a-z] - any one charecter in range of characters from a to z
[aeiou] - any one character from collection of characters
[!aeiou] - any one character by ignoring collection of characters( invert output)
{} - list of files with comma separator

specital files
.bashrc - file contain default setting for terminal. executed when terminal open.
.bash_logout - file containg script executed at the time of logout from terminal.

regular expressions patterns


* - zero or more characters
? - zero or one character
[a-z] - any one charecter in range of characters from a to z
[aeiou] - any one character from collection of characters
[^aeiou] - any one character by ignoring collection of characters( invert output)
. - any one character
^ - line starting pattern matching
$ - line ending pattern matching
| - work as or condition for two string (str1) | (str2)
\ - hide special meaning of character
\< - starting of word
\> - ending of word
\w - matching a-z,A-Z,0-9,_ characters
\W - matching other than a-z,A-Z,0-9,_ characters
\+ - one or more occurance
{n} - pattern match for number of time
{n,} - pattern match for number of time or greater than number
{n,m} - pattern match for minimum n time and maximum m time

/etc/rc.d - containg Booting time shell script


/usr/local/bin - Move shell file to this location for making shell file as command
Builtins(internal commands) executed faster than external commands

INTERVIEW QUESTIONS
1 what are basic elements or components of linux?
hardware – physical components like harddisk, ram, cpu, mouse, keyboard ect.
Kernel – its core of linux. Responsible for activities of OS like process mgmt, device mgmt.
Shell – its an environment in which we can run our commands. Interface between kernal and user.
System utilities – are program to perform specialized and individual level tasks. (like commands)
system library – set of functions or program to access the feature of kernel without writing code.

2 What do you mean by linux? Explain its features.


Linux is open source OS which manage the communication between software and hardware
by allowing access to the resources.
First released on 5oct 1991 by linus torvalds for computer(secure and faster than windows)
Flavors of linux – ubuntu, redhat, debian, suse, gentoo, kali,solaris(sun microsystem) ect.
Features
free and open source
more secure
multiprogramming system
GUI
robust and adaptable

3 what is bash?
Bash is command language interpreter, stand for Bourne Again Shell.
its Advanced edition of Bourne shell
its default user shell on most linux installation

4 what is kernel? Explain its functions.


Its core component of linux OS.
Act as resource manager between software and hardware.
Kernel is first program that is loaded whenever computer system starts.
Functions-memory mgmt, processs mgmt, device mgmt, storage mgmt, peripheral interfaceing.

5 what are two types of user modes?


CUI(Character user interface)
GUI(graphical user interface)

6 what is lilo?
Lilo (linux loader) is bootloader used to load linux into the memory.
If you want to install linux then you need to install bootloader i.e. lilo.
Also manage the dule booting option for computer.
Functions- locating kernel, identifying supported porgrams, loading and starting kernel.

7 what is swap space?


Swap space is virtual memory. When RAM is full then its used to extend memory.
Its space on hard disk to hold the program overloaded from RAM.
Swap space is initiated at the time of linux installation.
Space should be twice than RAM size or nearly same as RAM size.

8 what do you mean by process state in linux?


At the time of process execution it stay in number of state to complete execution.
New/Ready: a new process is created and is ready to run.
Running: the process is being executed.
Blocked/Wait: the process is waiting for input from the user and if doesn't have resources to run.
Terminated/Completed: the process has completed the execution or terminated by the OS.
Zombie: the process is terminated but information regarding the process still exists and is available
in the process table.
9 what is linux shell? types of shell.
Shell is interface between user and kernel.
Shell is program used by users for executing commands.
Shell read command from terminal, check the syntax, if its ok then send to kernel for execution.
Otherwise give error message with code on standard output
Types of shell
Bourne shell
BASH
CSH
TCSH
ZSH
KSH

10 type of modes used in vi editor.


Default text editor comes with most of linux OS. There are basically 3 types of mode in vi editor.
1 command/regular mode – its default to perform action on pressed command.
2 insertion/edit mode – allow to edit text into the file.
3 execution/replacement mode – to save file and perform operations on file it self.

11 what is maximum length of filename under linux?


Filename lentgh have maximum 255 bytes with extension.

12 explain file permission in linux


owners- user, group and others can operate on files and directories as per permissions.
Permissions – read, write and execute permissions allow to the owners for files and directories.
-rwxrwxrwx - first char indicate – for file d for directory, then rwx for user, next rwx for group,
final rwx for others.
umask and chmod – explain in basic

13 what is LVM and why it is required?


LVM stands for logical volume management.
LVM is tool that provides logical volume management for linux kernel.
By using LVM physical storage management getting easier.
It simply allows for flexible disk space managment.
Functions- allocating disks, striping, mirroring, resizeing volumes.
It required to resize the size of file system online.
lvextend – used to extend size of LVM partition
lvreduce – used to reduce size of LVM partition

14 what is difference between bin and sbin


bin -> contain binary executables related to normal user command.
sbin -> contain binary executables related to super user commands.

15 difference between / and root


/ -> act as root for linux file system, topmost directory in file system
root -> act as home directory for super user, sub directory of / directory

16 difference between mnt and media


mnt -> contain manual mounting files
media -> contain automatic mounting files
17 copy multiple file into single file
$cat file1 file2 fil3 > file4 (copy file1,file2,file3 content into file4)

18 view content of file from 50th line to 60th line


$tail -n +50 | head -n 11

19 difference between cat,touch,tee command


cat – view,create,append,copy file content
touch - create file with timestamp
tee – redirect previous cmd output as input to the next command as well as create file & save in it.

20 different between hardlink and softlink/symlink/symbolic link


hardlink –> same inode number, size, timestamp. Delete original file no effect on link file.
Softlink –> different inode number, size and timestamp. Its pointer to original file. Delete
original file will effect on like file.

21 what is file discripter and explain redirection operators


< or 0< - standerd input redirectional operator associated with keyboard
> or 1> or 2> - standerd output(1) and error(2) redirectional operator associated with terminal
file descriptor(0,1,2) - 0-stdinput 1-stdoutput 2-stderror

22 how to run multiple command on single line


$cmd1 ; cmd2 ; cmd3
$ cmd1 && cmd2 && cmd3

23 how to create alias permanantly


.bashrc -> save alias in this file
.bash_aliases -> create file and save alias in this file

24 difference between locate and find


locate find
1>search in database search in file system
2>have less number of options have number of options
3>search by name and permission only search by name,type,size, depth,age,
user,group,permission etc
4>we can not reduce depth of search we can reduce depth of search
5>produced result is not accurate produce accurate result
6>there is no way to use result can use produced result by -exec
7>operates fastly operates slowly

25 find all empty file and remove from current directory


$find . -type f -empty -exec rm {} \; -> remove without user prompting
$find . -type f -empty -ok rm {} \; -> remove file with prompting( yes or no)

26 find file size between 10k and 20k


$find . -type f -size +10k -size -20k

27 delete empty lines from file an/d display on stdout


$grep -v ‘^$’ file
28 search mobile number from file
$grep -w ‘[0-6][0-9]{9}’ file

29 find date pattern like dd-mm-yyyy or dd/mm/yyyy in file


$grep -w ‘[0-3][0-9][-/][01][0-9][-/][1-2][0-9]{3}’ file

30 find number of file in current directory


$ls -l | grep ‘^-’ | wc -l

31 convert all letter from small to capital in file


$tr [a-z] [A-Z] < file

32 what is zombie and orphan process?


Zombie – process execution is completed or kill by user still its entry in process table.
Orphan – process entry is in table but the parant process is not exist.

33 what is inode and pid


inode - uniq identification number for each file and directory in file system
pid - uniq identification number for each process in process table

34 how to check memory usage


$free
$vmstat
$top
$htop
$sudo cat /proc/meminfo

35 how to check disk usage


$df ->display file system disk usage
$du file/dir ->display file/directory size

36 which command is used to check or change default file and directory permissions
$umask

37 how to delete 21th line to end of file without openning it


$sed -i ‘21,$d’ file ->21 for starting (, for range) $ for last line d for delete i for permanant delete

38 how can we create and view hidden files


$cat > .filename -> create hidden file
$ls -a ->display all hidden files

39 list linux directory commands


$cd
$pwd
$ls
$mkdir
$rmdir

40 what is command substitution


$echo “current date:$(date)” -we can execute command (date) in another command (echo)
argument or parameter and produced output considerd as argument string

41 what is private IP address


private ip address is unique identification address within organaization access the host means we
cannot access this from outer world.

42 what is daemon
daemon is service or process running in background. Daemons listen the user request to perform
operation on that.

43 explain process management system call


system call provide interface between user program and operating system. Process management
system calls used to perform process related operations like create,kill,execute etc
fork(),wail(),exec(),exit(),getpid(),getpid(),nice()

44 how to rename file in linux


$mv oldfilename newfilename

45 which command is used to identify shell you are using


$echo “current shell: $SHELL”

46 what are the 3 standard stream in linux


standard output (stdout) – terminal
standard error (stderr) - terminal
standard input (stdin) - keyboard

47 find largest file in current directory


$ls -1Rs / | sort -nr | head -1

48 how do you stop a running process


By pressing ctrl+z

49 who does linux secure than windows


linux provide two level security
1> By assigning permission to file and directory
2> By authentication (providing passward)

50 enlist daily used commands


ls -lart
head
tail
pwd
cd
grep
find
top/(sar)
ps -ef
sed
ping
51 how can we access cmd line arguments in shell script
$0 -> executed command
$1 -> first argument
$2 -> second argument
$3 -> third argument
$* -> all argument
$@ -> all argument
$# -> number of arguments

52 where log files are stored in linux file system


In /var directory

53 create an empty file where filename contains current system date and time.
Touch “file$(date +%d%m%Y%H%M%S)”

54 how to create hirarachy of file directory using single command


by using -p optiong with mkdir command
Ex $mkdir -p dir1/{dir11,dir12}/dir000

54 what is the output of $echo $$


it display the process id of current bash shell

55 how do you access partitions under linux


/dev/hda1 -> access first harddisk partition
/dev/hda2 -> access second harddisk partition
/dev/hda3 -> access third harddisk partition

56 how to kill all jobs(processes) running in background


$kill -9 0 ->it will also kill the shell(terminal)

57 how can you insert comment in the command line


by using # we can insert comment in the command line
$ls # listing all file and directory

58 search pattern “mobile” in all .txt file in current directory


$find . -name “*.txt” | xargs grep -i “mobile”
-> xargs used to output of find (stdout) convert as stream for grep

59 what is the command to calculate the size of folder


$du -sh dirname -> s seperate for only directory not subdirectory & h for human readable

60 explain key combination of ctrl+alt+del in linux


ctr+alt+del work same as like windows(restart system). But no confiramation message is displayed.

61 enlist file viewing command in linux


$cat
$head
$tail
$more
$less
$pg
$vi -(by using any editor)
$view

62 what is builtin commands in linux and give some examples


builtin commands are internal command comes with shell. They are faster than external command.
Ex Alias,cd,echo,exit,export,help,history,jobs,kill,pwd,set,umask etc

63 which command is used to review boot messages


$dmesg

64 which file is used to automatically mount file system


Fstab file

65 what are the different types of file systems in linux


Ext, Ext2, Ext3, Ext4, JFS, XFS, Btrfs, Ufs, Autofs, Devpts, Ntfs, swap

66 how to find highest size contaning file or directory in current directory


$du -s ./* | sort -nrk 1 | head -1

67 how can you limit memory usages in linux


$ulimit -Sv 2000 -> 2000kb=2mb limit
$ulimit -Sv unlimited -> remove memory usages limit

You might also like