Sei sulla pagina 1di 32

UNIX Commands Made by Dharmesh Rathod

ls: Lists all the non-hidden files and directories

ls -l : Lists all non-hidden files and directories in long format

ls -F : List all the Ordinary files and directories. Identify by 'bin/'

ls -a : Lists all files and directories including hidden ones.

ls -r : Lists all files and directories in reverse alphabetical order.

ls -1 : Displaying only file name in a single column.

Ls -lh : Lists all non-hidden files and directories in long human

readable format.

Lsof: It will list down pid of all the process which using a particular

file.

ls -t : Lists all non-hidden files in the order they were last modified

Cat Files : To view the content of the file

cat -n files: its Number the output lines

cat -b files: Skip numbering blank line.

Wc -l : get count the number of line.

Wc -w : get count the number of word.

Wc -m or -c : count the number of character.

Which command : To see the execute command location

cd .. : Moves you to the directory that you want to go.

cd - : Moves you to the directory you just came from

cd ~ : Both move you to your home directory (the directory you start
from initially).

mkdir dirname : Creates a directory.

mkdir ~/left : Makes a directory in your home directory named left.

Mkdir {a,b,c}: To create multiple dir in single command


rm file1 file2 file3: Removes (deletes) file(s)

rm -i file1 file2 : Prompts before deletion of files *******USE -i AT


FIRST*******

rm -f file1 file2 : Forces deletion without prompt regardless of


permissions.

rm -r directory : rm -R directory : Remove a directory along with anything


inside of it

rm -fR name : rm -Rf name : This combination will force the removal of any
file and any directory including anything inside of it

rm -Ri directory : Deletes the contents of a directory and the directory if


it is empty by prompting the user before each deletion.

cp file1 newname: Copies a file (file1) and names the copy the new name
(newname)

cp -p name target : Preserves all permissions in the original to the


target.

cp -R directory target : Copies a directory and names the copy the new name
(target)

cp -f name target : Forces existing path names to be destroyed before


copying the file

Mv initial final: Renames files and directories.

Also moves files to other directories

mv script.exe ~/bin Moves the script.exe file to the bin directory that is
in the home (~) parent directory and it keeps its initial name

pwd : show the current directory to the screen.

top – display all running processes

PS : Show Information about active process.

PS -a: Shows information about all users.

PS -x: Shows information about processes without terminals

PS -e : Show Information about all the process.


Ps - f : Show all the process in full listening.

ps -u user_id : Shows all processes that are owned by the person with the
pertinent user_id

uname -a : show kernel information

Who : Tells you who is logged onto your server

who am I : Tells you your user information.

W: Displays whos online.

Passwd : Command to change password

PasswdFile : /etc/passwd → It will display UID details in 7 field like


login,encryptedpwd,grpid,desc,dafaultdir,defaultshell.

Set : It will show environment variable's + functions

Env : It will show only global variable's

oslevel : To check OS version.

IMP of .profile file


 Environment variables must be set in .profile file.
 /etc/profile : OS level profile file
 /home/profile: User profile file.
 To exec profile file . ./.profile
 Support in all the platform like Solaris, AIX, HPUX

Exit: Come out from the script

Break: Skip the next script

echo $SHELL : To see the default shell.

echo $0 : To see the current shell.

df system : Reports the number of free disk blocks

df -k : Show the space in KB data format

df -kh . : Show the space in GB data format

df -km : show the space in MB data format

df : show disk usage

du : show directory space usage


Head -10 Filename: Show the first 10 lines from the file.

Tail -10 Filename: Show the last 10 lines from the file.

Kill Processid: Stop the process with specifies process id

Kill -2 - first checks if the process can be stopped and then kill's

Kill -9 - Forced Kill

l -c string file : Searches and prints only the number of matches to the
screen

grep -i string file : Searches without regard to letter case

grep -n string file : Prints to the screen preceded by the line number

grep -v string file : Print lines that do not match are printed

grep -x string file : Only exact matches are printed

grep -E string file : to search for multiple pattern in the file.


(Ex: grep -e “Dharmesh|Rathod” filename) it will search Dharmesh and rathod
both and printed.

grep -l "ERROR:" *.log


Instead of normal output, prints just the names of input files containing
the pattern.

grep -L 'ERROR:' *.log


Instead of normal output, prints just the names of input files that contain
NO matches.

grep -m 10 'ERROR:' *.log


This option tells grep to stop reading a file after 10 lines are matched.

grep -q pattern filename


Suppresses output. The command still conveys useful information because the
grep command’s exit status

grep -o pattern filename


Prints only the text that matches, instead of the whole line of input. This
is particularly useful when implementing grep to examine a disk partition
or a binary file for the presence of multiple patterns.

grep -A 3 Copyright filename


Offers a context for matching lines by printing the 3 lines that follow
each match.
grep -B 3 Copyright filename
Same concept as the -A 3 option, except that it prints the lines before the
match instead of after it.

grep -C 3 Copyright filename


Above 3 and below 3 lines are printed after matching.

Grep -H Pettern *
It will print the lines that have matching pattern along with filename.

Grep '^Start' filename


Print the line that will start with word start

Grep 'end$' filename


Print the line that end with word end.

touch file : create or update file with current time stamp.

touch file{1,2,3}.txt: This will create file1.txt, file2.txt and file3.txt


(create multiple file in a single command)

cat > file : places standard input into file.

chmod octal file : change the permissions of file to octal, which can be
found separately for user, group, and world by adding:
● 4 – read (r)
● 2 – write (w)
● 1 – execute (x)

Examples:
chmod 777 – read, write, execute for all
chmod 755 – rwx for owner, rx for group and world.

Above is the Octal Method to give a permission.

Symbolic Method

chmod u+x → Exec Perm to user


chmod g+x → Exec perm to group
chmod o+x → Exec perm to owner
chmod a+x → Exec perm to all

To give all access to files in directories?

chmod a=r * or $ chmod guo=r *


To stop anyone except the owner of the file .profile from writing to it,
try this:

$ chmod go-w .profile

ssh user@host : connect to host as user

ssh -p port user@host : connect to host on port as user.

ssh-copy-id user@host : add your key to host for user to enable a keyed or
passwordless login

TAR – GZIP – BZIP2

-t : List the contents of an archive


-x : Extract file from an archive
-v : verbosely list file processed
-f : Specify an archive
-z : Decompress the content of the compressed archive created by .gz
-j : decompress the content of the compressed archive created by .bzip2

IMP: Find will not search the type or file-type in compressed file like
.tar, .gz, .bzip2 and also grep will not search pattern inside the .tar or
.gz or .bzip2

How to create .tar file

tar -cvf filename.tar filename ( to extract -xvf)

How to create .gz file

tar -zcvf create.tar.gz create.tar ( to extract -xvzf )

How to create .bzip2 file

tar -cjvf create.gz.bzip2 create.gz ( to extract -xvjf)

gzip file : compresses file and renames it to file.gz

gzip -d file.gz : decompresses file.gz back to file

Network
ping host : ping host and output results

who is domain : get who is information for domain

dig domain : get DNS information for domain

dig -x host : reverse lookup host

wget file : download file

wget -c file : continue a stopped download

echo $? : Show the last run command is successful or not. ( 0 than


successful or >0 than not successfully)

echo $0 : The file-name of the current script

echo $# : The number of arguments supplied on script

echo $$ : Show the process number of the current script.

echo $! : The process number of last background command.

echo $_ : Check the parameters passed in previous command. Eg : ls -l


-l is parameter. If you writes ls -ltr than -ltr is the parameter.

echo $0 : check the current parent process. Eg : -ksh

echo $* : show the parameters or argument name which you have define.

SCP : Securely transfer file between 2 computers.


In UNIX you can use 'SCP' to securely copy file and directories from one
computer to another computer without starting FTP Session. The 'SCP'
command are uses SSH to transfer the data. It requires password for an
authentication. Unlike Rcp and FTP. 'SCP' encrypt both the files. If any
password exchange so that anyone snooping on the network cannot view them.

Scp [option] username1@source_host:directory/filename


username2@source_host:directory/filename

RCP : Remote file copy

Copies files between one computer to another computer


Note: RCP is not secured and encrypted method of transferring files.

Syntax
rcp [-p] [-r] filename ….. directoryname
[-p] : Attempt to give each copy the same modification times, access times,
modes, and ACLs if applicable as original file.

[-r] : Copy each sub-tree rooted at filename; in this case the destination
must be a directory.

Example:

rcp /mydir/myfile hope:otherdir/myfile

Above command copies the file name “myfile” from the local path “ /mydir”
to the remote computer named “hope” and placing into the directory “/
otherdir”

IMP:

 RCP doesn’t properly handle symbolic file. Use tar or cpio piped
to rsh to obtain remote copies of directory containing symbolic file.
 RCP doesnt support ACLs.

Rsh: Remote Shell - Execute command on host.


Rsh copies its standard input to the remote command, standard output of the
remote command to its standard output and standard error of the remote
command to its standard error. Interrupt,quit, termination signals are
broadcast to the remote command.

Rlogin – Remote login – starts a terminal session on remote host host

In our scripts we have the below line as the first line in every script
#!/bin/ksh/ u know what this line means?

Its invokes the ksh shell. its called sha-bang


so no matter which shell you are working on, it will also execute script as
per ksh.

What is the difference between ls -ltr and ls -lrt?

Both retrieve the non-hidden files and directories in asc order.

UNIX Process and how its works? And which 2 files are running while login
in UNIX?

Process :
1./ SSH D process will run first.
2./ INIT Process will run after SSH D
3./ Once appears log-in screen on that time Getty process will run. Than
you log-in with user name and password.

Two Files are running in back end.


1./ Password File (./etc/password)
2./ User Profile File

How to connect to oracle db from UNIX terminal?

Steps as below:

 Two environment variable must be exported ORACLE_HOME & TNS_ADMIN must


be set.
 export ORACLE_HOME=<Path to oracle home directory>
 export TNS_ADMIN=<Path to TNSNAME.ORA file having the TNS entry of db
to connect>
 Then do this command
 $ORACLE_HOME/bin/sqlplus userid@dbschema/password

I have one file with name “abc.ksh”. I want to check the file current
location?

find . -name "abc.ksh"

What is the difference between UTILITY and COMMAND in UNIX?

Utility

 Utilities are programs you can run or execute. The programs who and
date.
 Every Programme consider a utility.
 The term utility refers to the name of a program

Command
 Term command refers to the program and any arguments you specify to
that program to change its behavior

How login start a shell Interactively?

$ /bin/sh

l On HP-UX, it is the POSIX shell.


l On Linux, it is the Bourne Again shell.

How login start a shell Non-Interactively?

$ /bin/sh Login

Ex: Put this 2 command in file Login and type as above. (Login is filename)
How to make shell script executable?

Chmod a+x logins ( permissions )

logins.ksh or ./logins.ksh ( executed )

What is the purpose of following command #!/bin/sh?


To ensure that the correct shell is used to run the script

What are the two files used by the shell to initialize itself?

./password
./user-profile file

How to set PATH / MANPATH in UNIX and why its needed?

PATH is used to set the default Path to search for when any program/binary
is executed.

PATH=$PATH:/bin/. (it will add . In /bin location)

MANPATH is used to set the path to search when man command is executed

MANPATH=/usr/man:/usr/share/man

(Each of the individual entries separated by the colon character ':')

You can also check all the shell options with the following

set -o ( to enable and disable shell option like monitor, keyword,vi on off
etc)

To Enable : set -o monitor


To Disable: set +o monitor

How do you run a command in the background?

We can run a process in background using & (an ampersand) at the end of the
command you run the job.

To check the status of the job : PS


To bring background to foreground process : fg jobnumber
To bring foreground to background process : bg jobnumber
If you have more then one job suspended in background : fg %#

How to replace text Dharmesh with citi in Vi Editor?


$:%s/Dharmesh/Citi/g

How do I replace on the current line only.

$:s/Dharmesh/Citi/g

How do I replace all lines between line 10 to 100?

$:100,200s/Dharmesh/citi/g

How do I replace with case sensitive find and replace?

$: %s/DHARMESH/dharmesh/gI or Ic

How do I replace with case insensitive find and replace?


Like unix,Unix,UNIX,unIX etc...

$: %s/UnIx/dharmesh/gi or ic

Find and replace with confirmation?

$: %s/Unix/dharmesh/gc

How to define variable's?

#!bin/sh/

NAME=”ABC”
SURNAME=”BCD”

echo $NAME
echo $SURNAME
How to define Array and Values in Array?

array_name[index]=value
like as below

NAME[0]=”Dharmesh”
NAME[1]=”Sanjay”

To initialize Array
set -A array_name value1 value2 ...valuen (for KSH)

echo “FIRST NAME: ${NAME[0]}”


echo “SECOND NAME: ${NAME[1]}”

output
Dharmesh
Sanjay

We can access all the item in once as below


${array[*]}
${array[@]}

echo “FIRST NAME: ${NAME[@]}”


echo “SECOND NAME: ${NAME[*]}”

Output:
Dharmesh Sanjay

How do i remove the file whose name begins with a "-"(File in current
directory)

rm ./"-"filename

Write a command to kill last background job.

Kill $!

How do you identify hidden file

ls -la

To differentiate between devise file and ordinary file kernal check the
file 'type' field in file structure.

a. True
b. False

How do you change the priority of existing process?

nice

What does adding '&' at the end of the command means

Runs process in background

For grep command -v option

Only Non-Matched records can be printed.

For tail command -F option

Option causes the command to continuously print additional line as they are
written.
tar zcvf tar_files command will-
a. Extract the content of the specified tar file. The z option specified
that the tar file has been compressed.

b. concatenate tar file with the specified name, containing the specified
file and their sub-directory the z option specified that the file will be
compressed.

c. Create tar file with the specified name, containing the specified file
and their sub-directory the z option specified that the file will be
compressed.

d. delete the tar files

To append to end of the file , you will

use >>

To redirect the error output of the command does

a. command 2> file


b. command2> /dev/null

Write a command to display the second and fourth character from each line
of a file?

Cat filename | cut -c2,4

Write a command to display the second and fourth Word from each line of a
file?

cat test_file | cut -f2,4

Write a command to display the files in the directory by file size?

$ ls -l | grep '^-' |sort -nr -k 5 (5 stead of colum same like sql)

How to list the files that are accessed 1 day ago in the current directory?

$ find . -atime 1 -type f

How to list the files that were modified 1 days ago in the current
directory?

$ find . -mtime 1 -type f

How to list the files whose status is changed 2 days ago in the current
directory?

$ find . -ctime 2 -type f

Write a command to display your name 5 times.

The Yes utility can be used to repeatedly output a line with the specified
string or 'y'.

$yes 'DHARMESH' | head -5

Write a command to replace the word "MANAGER" with "(MANAGER)" in a file?

$ sed 's/MANAGER/(&)/g' Filename


Write a command to print the lines that has the the pattern "SALESMAN" in
all the
files in a particular directory?

$ grep MANAGER *
$ grep -i manager * ( I : without regard letter case)

Write a command to print the file names in a directory that contain the
word "MANAGER"?

$ grep -li manager *

How to create an alias for the complex command and remove the alias?
The alias utility is used to create the alias for a command. The below
command creates alias for "ls -l" command

$ alias ll='ls -l'

If you use ll, it will work the same way as ls -l.


To remove the alias simply use the unalias command as

$ unalias ll

Write a command to display todays date in the format of 'yyyy-mm-dd'?


The date command can be used to display todays date with time

$ date '+%Y-%m-%d'
2012-07-12
To find the no of blank line in a file?

$grep '^$' file1 | wc -l

FTP Command

lcd : change the local current directory


get : Download file from the FTP server
put : Transfer the file and place it to FTP server
mget : To download multiple file from FTP server
mput : To Transfer multiple file to FTP Server
prompt: to turn on/off interactive mode.
Binary: to turn on binary mode.
Ascii: to turn on Ascii mode.
Delete: to turn a file on FTP server
status: to display current FTP session configured.
Mkdir: to make directory on FTP server
quit/close/bye/disconnect: to disconnect from FTP server

Example:

Sftp dr12889@myservername
lcd <dir>
cd <remote server dir>
get <files> (from myserver)
put <files> (to myserver)
bye/disconnect/quit (disconnect from the FTP server)

FIND

IMP points to note


to search in home directory : $HOME (find $HOME -name filename)
to search in root directory : / (find / -name filename)
to search in current directory : . (find . -name filename)
to search in current directory : | tmp (find | tmp -name filename)

find $HOME -name dharmesh -type f


This start the search in the directory $HOME and looks for a file named
dharmesh

find $HOME -name dharmesh -type d


This start the search in the directory $HOME and looks for a directory
named dharmesh

find / -name dharmesh -type d


This start the search in the directory in root and looks for a directory
named dharmesh

find / -name dharmesh -type f


This start the search in the directory in root and looks for a file named
dharmesh

IMP:

More than 1days we need to use +1


Less than 1days we need to use -1
Exact day we need to use 1

find / -mtime -1
This start the search at the root directory and looks for all file which
were modified 1day ago

find / -ctime -1
This start the search at the root directory and looks for all file which
were changed 1day ago

find / -atime -1
This start the search at the root directory and looks for all file which
were accessed 1day ago

find / -atime +5
This start the search at the root directory and looks for all file which
were accessed MORE THEN 5 DAYS ago

find / -mtime -1 2> /dev/null

This starts the search at the root directory and looks for all file which
were modified 1day ago and sending all 'permission denied' message to the
bit bucket.

What command will find all filenames ending with .HTML?


Find / -name *.html

what command will find all files belonging to username?


Find / -user username

What command will find a directory named nethelp starting in the /var
directory?
Find /var -type d -name nethelp

What command will suppress the display of the “permission denied” messages
that are displayed when you use the find command?
Find / -name filename 2> /dev/null

what command will find all the empty directory?


Find / -type d -empty

How to find all the files or directories which holds 777 permission in UNIX
Box?

Find / -perm 777

How to delete temporary files using find command in UNIX?


Find / -name “*.tmp” -print | xargs rm -i

How to find all text file which contain word exception using find command
in UNIX?
Find . -name *.txt -print | xargs grep “Exception”

Find the file in current directory not on sub-directory


find . -maxdepth 1 -type f -newer Filename

How to find the file based on the file Size?


Find . -size +1000c -exec ls -l {} \; (c specify the size in byte)

How to find the file some days older and above certain size?
Find . -mtime +10 -size 50000c -exec ls -l {} \;

Find everything in your home directory that has NOT been modified in the
last year:
find $HOME -mtime +365

Write a command to display the files in the directory by file size?


ls -l | grep '^-' | sort -nr -k 5

How to find multiple filetype in directory.


Find . -name “*.text” -o -name “*.html” * -o filename
Find . -name “*.text” -or -name “*.html” * -o filename

To find html files that have been modified in the last seven 24-hour
periods (days), I can use -mtime with the argument -7 (include the
hyphen):

find . -mtime -7 -name "*.html" -print

To find those html files that I haven’t touched for at least seven 24-hour
periods (days), I use +7:
find . -mtime +7 -name "*.html" -print

SED :

Sed is stand for Stream editor. One of the most common use of sed is text
subsitution. Eg: Replacing certain text with something else.

Which following command will subsitute (Find and Replace) 'FOO' to 'BAR'
globally.

sed 's/foo/bar/g'

Which is the following command will print 10lines of file using 'sed'

sed 10p

How to display the 10th line of a file?

Sed -n '10p' filename

Write a command to find the length of 11th line in a file?

sed -n '11p' Filename | wc -c

How to get the 2nd word of 11th line of a file in Unix?

$ sed -n '11p' Filename | cut -f2 -d'|' ( if | thn -d'|' or if ' ' than -d'
')

How to get the last word from 11th line of a file in Unix file?

$ sed -n '11p' Filename | rev | cut -f1 -d'|' | rev

How to display the first 10 lines of a file?


sed -n '1,10p' Filename

Write a command to print the last line of a file?

$ sed -n '$p' Filename ( $ for last line )

***APPEND LINES***

sed provides the command “a” to append line after every line with the
address or pettern.

Add a line “Hello”

*****SED in VI EDITOR*****

Find and Replace with dharmesh to dharmesh123 globally

%s/dharmesh/dharmesh123/g

Find and Replace with confirmation

%s/dharmesh/dharmesh123/c

Find and Replace with case insentive

%s/dharmesh/Dharmesh123/gi

Find and Replace with case-sensetive

%s/DHARMESH/dharmesh123/gI

Find and replace in current line only

:s/dharmesh/dharmesh123/g (remove the '%' substitution from command '%'


make changes on all lines)

Find and replace all lines between 100 to 200

:100,200s/dharmesh/dharmes123/g

*****DEBUGGING IN UNIX*****
There is two technique for debugging shell scripting
1./ Syntax checking
2./ Shell Tracing

#!bin/sh opt : these methods for enabling debugging modes take effects when
script is invoked. so its refereed as invocation activated mode

Debugging option for shell scripts

set -n : Reads all commands, but does not execute them


set -v : Displays all lines as they are read.
set -x : Displays commands and their arguments as they are executed.
Set -e : in non-interactive mode, exit immediately if a command fails
Strace : is also useful to see whats going on. Especially useful if you
have not written the script your self.

When one of the debugging options is activated, a letter corresponding to


that option is added to the variable $-. For example, if the -v (verbose)
option is used, the letter v is added to $-. Similarly when the -x is used,
the letter x is added to $-.

example:
case $- in
*v*) : #verbose mode
;;
*x*) : #Shell trace Mode
;;
esac debugging modes

1./ You can use the set command to disable a debugging mode as follows: set
+opt
2./ To enable shell tracing in debug mode : set -x
3./ To Disable Shell tracing in debug mode : set +x
4./ To disable any and all the debugging mode that have been enabled : set
-
5./ To enabling dubbing for single function : set -x ; toDate; set +x
(toDate is function name)
6./ To see where the script produce the error : Sh -x script argument

To enable syntax checking use -n

Example:

#!/bin/sh

YN=y
if [ $YN = "yes" ]
echo "yes"
fi

output : syntax error at line 7: 'fi' unexpected

to debug the script file : sh -x filename.ksh

Common question:

How to print/display first line of the file?

Head -1 filename or sed '2,$ d' filename

How to print/display last line of the file?


Tail -1 filename or sed -n '$ p' filename

How to remove header from the file?


Sed '1 d' filename

How to remove footer from the file?


sed '$ d' filename

How to remove certain line from the file?


Sed -i '2,3 d' file.txt

How to find patterns next 3 lines?


Sed -n '/Pettern/{n; p; n; p; n; p;}' Filename

How to find which shell I am working on?

Echo $SHELL
result : /bin/bash

IMP : If you type only SHELL or $SHELL it gives you an error state command
is not found.
What is inside the /bin?
Inside the /bin folder we can find all the commands.exe which we are
usually executing on UNIX terminal.

How to replace ' '(space) with , (comma) in UNIX?

If I don’t write #!/bin/sh and execute the script file then what will
happen ? It gives me an error or it will successfully execute.

#!/bin/sh its called shebang in UNIX speak # is called hash or sharp and !
Is called bang. So when you put together you will get hash bang or shebang

The after #! tells unix what program to use to run it. If it will not
specified then it will try with bash,sh,ksh or zsh or whatever shell
variable's is but it its there it will use that program. Plus # is comment
in most of the language so the line gets ignored in future execution.

Or

Known as a interpreter line. If you not specified by default it takes


bash,sh,ksh or zsh

Network related questions

different tyes of network in linux ?

lspci : list of PCI devise


lshw : list all hardware
dmidecode : list all hardware data from BIOS
Ifconfig : outdated net config utility
ip : recommanded new network config

netstat command ?
Its provide socket level and port no information.

how to stop firewall from command promt in Linux?


Chkconfig iptable on or off

How to change IP Address in UNIX?


ifconfig eth0 ipaddress netmask maskaddress

how to stop firewall from command promt in windows ?


netsh firewall set opmode disable or enable

What is the difference between telnet and ipadd in unix?

Telnet : Checks whether port number and ipaddress is available or not


Ipadd : Checks for network connectivity.
Some tricky commands

How to change current time with last time stamp?


Touch -t 201409121200 filename

red : Date and Green : time

How to change the login shell?

Chsh -s /usr/bin/ksh or sh or bash

EX: Enter the command cat /etc/passwd


grep “your pwd” /etc/passwd
and perform above command.

Job control command list?

& → run the command in background


Ex: ls -l &

ctrl -z → stopped the foreground process


Ex: ctrl -z (Stopped)

jobs : List background process


Ex : Jobs

%n : Refer to the background number


Ex : fg %1

%?str : Refer to the background str


Ex : %fg %?ls

bg : Restart stopped background process


Ex : %bg

fg : Bring process from background to foreground


Ex : fg %1

Kill : Kill a process

How to find which process are taking more memory? Or How will you get top
consuming process?

Ans : From inside the TOP you can try below


PRESS shift + f
Press the letter corresponding to %MEM
Press ENTER

or

How to find TOP 5 process which is taking more memory?


ps -eo pmem,pcpu,vsize,pid,cmd | sort -k1 -nr | head -5

The 4 PS of ITIL Service Management as below

People : Considering the people that work in IT Services. also ensure the
following.

Their staff have the skill to match the role, Their Support,
Responsibility, communications, Customer Relationship etc...

Process : Definition of process is 'Set of coordinated activities combining


and implementing resource and capabilities order to produce an outcome
which creates the value for a customer or stockholder.

each process have owner whose role includes following...

1. Process Strategy
2. Process Design
3. Process Documentation
4 .Resource Training

Product (Technology) : Its depends upon the following technology

1. Own Technology product for support


2. Monitoring tool
3. Support tool
4. Automation
5. Communication Tool

Partner (Supplier) : Partner have a big impact on IT service. The staff


depend upon a third parties to deliver goods or services needed to run IT
service.
Its IMP to have proper SLA to be formed

How will you find a file in current directory without searching the file in
sub directory?

Example : I have directory called Dharmesh and inside the Dharmesh I have
many sub-directories so what I want is to find the file in only Dharmesh
directory instead of all sub-directory.

Find /Dharmesh -maxdepth 1 -type f

What is iNode in UNIX?

Its referred as Index Node.


Its a file structure on a file system more easily its a “Database” of all
file information except the file content and file name.

What is the largest size of the file support in UNIX?

Its depends upon the how much space is available in either /var/tmp (VI
Temp location)also I had a case where I had to split the file into serval
once like

VI Limitation is 90700000 char or max Filesize is 2GB

split -l 5 file tf
then editing them using

vi tf*
then rejoining them using '>>'operators

How do you find which remote hosts are connecting to your host on a
particular port say 10123?

Netstat
ex : netstat -a | grep 'port'

What is ephemeral port in UNIX?


ephemeral port are port that used by OS for client socket. There is a
specific range on which OS can open any port specified by ephemeral range.

How to list of file/folder alphabetically in UNIX?


Ls -l

If once process is inserting data into your mssql database? How will you
check how many rows inserted in every second?

Watch

Your Application home directory is full? How will you find which directory
is taking how much space?

Du -sh | grep G will list down all the files which have GIGS in size.

How to find how many days your server is up?


Uptime

How to execute DB store procedures from UNIX?

> SqlReturnMsg=`sqlplus -s username/password@database<<EOF


BEGIN
Pro_your_procedure ( input parameters )
END;
/
EXIT;
EOF`

>echo $SqlReturnMsg

How to remove first line from the file?


Sed -i '1 d' filename

How to remove last line from the file?


Sed -i '$ d' filename

How to remove certain line from the file?


Sed -i '8,10 d' filename

What is difference between Softlink and Hardlink?

Softlink : Softlink is a file that have information to point to another


file or inode and that inode point to the data on the hard drive.

Command : ln -s /usr/bin/gedit ./desktop/gedit

When to use Softlink

Link across to file system: If you want to link file across the file system
Link to Directories: If you want to link directories than you must be using
soft-link as you cant create hard-link to directories.

Command : ln /usr/bin/gedit ./desktop/gedit

When to use Hardlink?


Hardlink: Hardlink is direct point to the original inode of the original
file. If you compare the original file with hard drive, there wont be any
differences.

Storage Space: Hardlink takes very low amount of space as there are no new
nodes created. Softlink takes the space of 4KB or depends upon the
filesystem.

Performance: Hardlink performance is better than softlink as you are


directly accessing the disk pointer instead of pointing to another file.

Moving File Location: If you move the source file to some other location on
the same filesystem than hardlink will work softlink will not.

Redundancy: If you want make sure saftly of your data you should use
hardlink. As in hardlink data is safe until all links to the files are
deleted. In softlink you will lose the data if master instance of file is
deleted.

More questions and Answer on Hardlink and Softlink

What is main difference between hardlink and softlink?

Softlink will have different inode number than the source file and hardlink
using the same inode number as the source file.

How to find all the softlink file in my system?


Find /etc -type l -exec ls -li {} \;

How to find all the hardlink file in my system?


Find / links +2 -type f -exec ls -li {} \;

How to find whether a file is softlink or not?


Simply ls -l it will tell whether it will pointing to another file or not

How to check whether a file have any softlink pointing to it?


Find . -lname '*folder'

How can I find out the source file of hardlink?


Nope, you cant find out the source file of the hardlink. Once hardlink is
created no one tell which was the first file created.

Can I make softlink to hardlink and vice varsha?


Yes, both acts as a normal file of the file system so you can do both.

What is UMASK and how to setup default UMASK in UNIX?


UMASK is used to determine the file permission for newly created files.
We can set the permission with symbolic value and octal value

When user create a file or directory under UNIX.Creates with set of


permissions like text file has default permission is 666 and similar
directory with 777.

How to calculate umask?

0 : read, write, execute.


1 : read, write
2 : read, execute
3 : read only
4 : write and execute
5 : write only
6 : execute only
7 : No permission

Now you can use the above calculation file permission for exmple: umask set
to 077 so how it will calculate as below

0 – Owner – r,w,x
7 – group – no permission
7 – others – no permission

How to setup default umask?


You can setup UMASK in /etc/bashrc or /etc/profile file for all the users.
Ex: vi /etc/profile
umask 022

save and close the file.


Please note: Change will effect after next login.

Explain UMASK 022

umask 022 for Normal user: Used for normal user. With this mask default
directory permission are 775 and default file permission 664

umask 022 for Root user: Used for root user. With this mask default
directory permission are 755 and default file permission 644

umask 022 for directories: Base permission are 0777 (rwxrwxrwx) and for
file is 0666 (rw-rw-rw)

in short:
umask 022 : allow to write a date but anyone can read the data.
Umask 077: its completely provide system like no one can read or write the
data it umask setted 077.
TOP

Top command is used to see the information about all the active process.
CPU Usage, Memory Usage, Running time and program name etc…

SHIFT + M == List process according to the memory usage.


SHIFT + P == List process according to the CPU Usage.
SHIFT + W == for saving the top output in the file (/root/toprc.)
SHIFT + O == for sorting the process as per the requirement.

ROW1

TOP 03.06.34 == Current System time.


Up 53days 40min == System up time.
3users == Current Users.
Load avg 2.4.5.2 == CPU Avg load.

ROW2
Task: 123 Total == Total process in active mode.
2 running == currently running process.
3 stopped == Currently Stopped process.

ROW3: CPU Usage Information


ROW4: Memory Usage Information

TOP Command

C (Press) == List running process with absolute path


K (Pid) == For killing the process
Z (Press) == List running process in color
R (pid) == For renice a process
1 (press) == shows the details of individual cps running on the system
D (press) == change the refresh rate.

VI: is used to create a new file or edit an existing file


VI Filename == create a new file or open an existing file if its
already created.

VI –R Filename == open an existing file in read-only mode

View Filename == open an existing file in read-only mode

:q! == exit without save any changes.

:w == Save the changes which have made.

:wq == Save and exit with changes made.

ZZ == same as wq.

Moving cursor == k(up), j(down), h(left), l(right).

W == position cursor to the next word


B == position cursor to the previous word

N| == Move to the column nth in the current line (10| with


move to the 10th column in the current line).

1G == First line of the file


G == Last line of the file

:n == Move to the nth line (:10 it will move to the 10th line)

H == Move to the top of the screen


nH == Move to the nth of the top of the screen (5H will move
to the top 5th line)

M == Move to the middle of the screen


L == Move to the bottom of the screen.

CTRL+D == Move forward to ½ screen


CTRL+F == Move to the full screen
CTRL+U == Move backward to ½ screen
CTRL+B == Move backward to fullscreen

i == insert text before current cursor location


I == insert text beginning of the currnet cursor location.
a == insert text after current cursor location
A == insert text at the end of the current line.
o == Create a new line below current cursor location
O == Create a new line above current cursor location

x == delete the character under the current cursor location


X == delete the character before the current cursor location
Dd == delete the entire line
D^ == delete the current cursor location to beginning line
D$ == delete the current cursor location to end of the line
Yy == copy the current line
Yw == copying the current word from the character
p == paste text after the cursor
P == paste text before the cursor

:f filename == rename current file to new filename


:w filename == write to the file filename
:e filename == open another file with filename
:cd dirname == change current directory to another dir name

:n == incase if you have open multiple vi file then it :n go


to the next file
:p == incase if you have open multiple vi file then it :n go
to the previous file

:set nu == display line with line number on the left side


:set ro == change filetype to read only.

How Do I Find The Largest Top 10 Files and Directories On a UNIX?

du -a /dirame | sort -n -r | head -n 10

du command -h option : display sizes in human readable format (e.g., 1K,


234M, 2G).
du command -s option : show only a total for each argument (summary).
du command -x option : skip directories on different file systems.
sort command -r option : reverse the result of comparisons.
sort command -h option : compare human readable numbers. This is GNU sort
specific option only.
head command -10 OR -n 10 option : show the first 10 lines.

How to find a largest file in directory

ls -lrt | sort +4n | tail

HTML Code:

ls -lrt -- will sort the file based on list and recent time modified
sort +4n -- will sort the ls -lrt output based on the column 4 which is size
tail -- will give you the last 10 lines , if you use tail -1 then you will
get the largest file alone

How to find out only TOP size file only?


# find ­type f ­exec du ­Sh {} + | sort ­rh | head ­n 5

How to kill the process which is under one of the group?

Pkill -TERM -P 27888 (Parent ID) it will kill all the process in PS 27888

How to find the process group ID using grep. For example, to kill my-script.sh's process group.

kill -TERM -$(pgrep -o my-script.sh)

What is the use of .profile file in UNIX? And I have a login with my username and password.
Where would my .profile file reside. Can i edit it?

First: the ".profile" is the user run control file (hidden file) that contain the list of the environment
Variables for your session as well as any commands you wanna to run upon your login.

Second: this file is loaded every time you login to your system using telnet/ssh and it is located
Under your home directory and you can edit it as well.

What’s the use of xargs?

If you just use a pipe, it receives data on STDIN (the standard input stream) as a raw pile of data
that it can sort through one line at a time. However some programs don't accept their commands
on standard in, they expect it to be spelled out in the arguments to the command. For
example touch takes a file name as a parameter on the command line like so: touch file1.txt.
If you have a program that outputs filenames on standard out and want to use them as
arguments to touch, you have to use xargs which reads the STDIN stream data and converts each
line into space separated arguments to the command.

Potrebbero piacerti anche