Linux Commands
Linux Commands
Linux Commands
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)
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.
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
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
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)
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
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
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)
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
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
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.
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).
$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
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
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
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
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
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
terminal shortcuts
ctrl + alt + t - open terminal
ctrl + d - close terminal
ctrl + z – stop current command or process and give command prompt
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.
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.
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
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.
36 which command is used to check or change default file and directory permissions
$umask
42 what is daemon
daemon is service or process running in background. Daemons listen the user request to perform
operation on that.
53 create an empty file where filename contains current system date and time.
Touch “file$(date +%d%m%Y%H%M%S)”