Ls Comands
Ls Comands
http://www.thegeekstuff.com/2010/11/50linuxcommands/
http://publib.boulder.ibm.com/infocenter/aix/v6r1/index.jsp?
topic=/com.ibm.aix.cmds/doc/aixcmds1/cp.htm
Table of Contents
ls command ...............................................................................................................................................6
Open Last Edited File Using ls -t..........................................................................................................6
Display One File Per Line Using ls -1..................................................................................................6
Display All Information About Files/Directories Using ls -l................................................................6
Display File Size in Human Readable Format Using ls -lh..................................................................7
Display Directory Information Using ls -ld..........................................................................................7
Order Files Based on Last Modified Time Using ls -lt.........................................................................8
Order Files Based on Last Modified Time (In Reverse Order) Using ls -ltr.........................................8
Display Hidden Files Using ls -a (or) ls -A...........................................................................................8
Display Files Recursively Using ls -R..................................................................................................9
Display File Inode Number Using ls -i.................................................................................................9
Hide Control Characters Using ls -q.....................................................................................................9
Display File UID and GID Using ls -n..................................................................................................9
Visual Classification of Files With Special Characters Using ls -F....................................................10
Visual Classification of Files With Colors Using ls -F.......................................................................10
Useful ls Command Aliases................................................................................................................10
cd command examples.............................................................................................................................10
To change the current working directory to the login (home) directory.............................................11
To change to an arbitrary directory.....................................................................................................11
To go down one level of the directory tree ........................................................................................11
To go up one level of the directory tree..............................................................................................11
Use cd alias to navigate up the directory effectively...........................................................................11
Perform mkdir and cd using a single command..................................................................................13
Use cd - to toggle between the last two directories.........................................................................13
pwd command..........................................................................................................................................13
man command .........................................................................................................................................13
which command.......................................................................................................................................14
whereis command ...................................................................................................................................15
whatis command .....................................................................................................................................15
uname command .....................................................................................................................................15
mkdir command.......................................................................................................................................15
To create a new directory in the current working directory, ........................................................16
To create a new directory with permissions...................................................................................16
To create a new directory with default permissions in subdirectory.............................................16
rmdir command........................................................................................................................................17
To empty and remove a directory...................................................................................................17
To remove the subdirectory ...........................................................................................................17
touch command........................................................................................................................................17
ls command
OpenLastEditedFileUsinglst
Toopenthelasteditedfileinthecurrentdirectoryusethecombinationofls,headandvi
commandsasshownbelow.
lstsortsthefilebymodificationtime,showingthelasteditedfilefirst.head1picksupthis
firstfile.
$vifirstlongfile.txt
$visecondlongfile.txt
$vi`lst|head1`
[Note:Thiswillopenthelastfileyouedited(i.esecondlongfile.txt)]
DisplayOneFilePerLineUsingls1
Toshowsingleentryperline,use1optionasshownbelow.
$ls1
bin
boot
cdrom
dev
etc
home
initrd
initrd.img
lib
DisplayAllInformationAboutFiles/DirectoriesUsinglsl
Toshowlonglistinginformationaboutthefile/directory.
$lsl
rwr1rameshteamdev9275204Jun1315:27mthesaur.txt.gz
1stCharacterFileType:Firstcharacterspecifiesthetypeofthefile.
Intheexampleabovethehyphen()inthe1stcharacterindicatesthatthisisanormalfile.
Followingarethepossiblefiletypeoptionsinthe1stcharacterofthelsloutput.
Field Explanation
normalfile
ddirectory
ssocketfile
llinkfile
Field1FilePermissions:Next9characterspecifiesthefilespermission.Each3characters
referstotheread,write,executepermissionsforuser,groupandworldInthisexample,rwr
indicatesreadwritepermissionforuser,readpermissionforgroup,andnopermissionfor
others.
Field2Numberoflinks:Secondfieldspecifiesthenumberoflinksforthatfile.Inthis
example,1indicatesonlyonelinktothisfile.
Field3Owner:Thirdfieldspecifiesownerofthefile.Inthisexample,thisfileisownedby
usernameramesh.
Field4Group:Fourthfieldspecifiesthegroupofthefile.Inthisexample,thisfilebelongsto
teamdevgroup.
Field5Size:Fifthfieldspecifiesthesizeoffile.Inthisexample,9275204indicatesthefile
size.
Field6Lastmodifieddate&time:Sixthfieldspecifiesthedateandtimeofthelast
modificationofthefile.Inthisexample,Jun1315:27specifiesthelastmodificationtimeof
thefile.
Field7Filename:Thelastfieldisthenameofthefile.Inthisexample,thefilenameis
mthesaur.txt.gz.
DisplayFileSizeinHumanReadableFormatUsinglslh
Uselslh(hstandsforhumanreadableform),todisplayfilesizeineasytoreadformat.i.eM
forMB,KforKB,GforGB.
$lsl
rwr1rameshteamdev9275204Jun1215:27archlinux.txt.gz*
$lslh
rwr1rameshteamdev8.9MJun1215:27archlinux.txt.gz
DisplayDirectoryInformationUsinglsld
Whenyouuselslyouwillgetthedetailsofdirectoriescontent.Butifyouwantthedetails
ofdirectorythenyoucanusedoptionas.,Forexample,ifyouuselsl/etcwilldisplayallthe
filesunderetcdirectory.But,ifyouwanttodisplaytheinformationaboutthe/etc/directory,
useldoptionasshownbelow.
$lsl/etc
total3344
rwrr1rootroot15276Oct52004a2ps.cfg
rwrr1rootroot2562Oct52004a2pssite.cfg
drwxrxrx4rootroot4096Feb22007acpi
rwrr1rootroot48Feb82008adjtime
drwxrxrx4rootroot4096Feb22007alchemist
$lsld/etc
drwxrxrx21rootroot4096Jun1507:02/etc
OrderFilesBasedonLastModifiedTimeUsinglslt
Tosortthefilenamesdisplayedintheorderoflastmodificationtimeusethetoption.You
willbefindingithandytouseitincombinationwithloption.
$lslt
total76
drwxrwxrwt14rootroot4096Jun2207:36tmp
drwxrxrx121rootroot4096Jun2207:05etc
drwxrxrx13rootroot13780Jun2207:04dev
drwxrxrx13rootroot4096Jun2023:12root
drwxrxrx12rootroot4096Jun1808:31home
drwxrxrx2rootroot4096May1721:21sbin
lrwxrwxrwx1rootroot11May1720:29cdrom>media/cdrom
drwx2rootroot16384May1720:29lost+found
drwxrxrx15rootroot4096Jul22008var
OrderFilesBasedonLastModifiedTime(InReverseOrder)Usinglsltr
Tosortthefilenamesinthelastmodificationtimeinreverseorder.Thiswillbeshowingthe
lasteditedfileinthelastlinewhichwillbehandywhenthelistinggoesbeyondapage.Thisis
mydefaultlsusage.AnytimeIdols,IalwaysuselsltrasIfindthisveryconvenient.
$lsltr
total76
drwxrxrx15rootroot4096Jul22008var
drwx2rootroot16384May1720:29lost+found
lrwxrwxrwx1rootroot11May1720:29cdrom>media/cdrom
drwxrxrx2rootroot4096May1721:21sbin
drwxrxrx12rootroot4096Jun1808:31home
drwxrxrx13rootroot4096Jun2023:12root
drwxrxrx13rootroot13780Jun2207:04dev
drwxrxrx121rootroot4096Jun2207:05etc
drwxrwxrwt14rootroot4096Jun2207:36tmp
DisplayHiddenFilesUsinglsa(or)lsA
Toshowallthehiddenfilesinthedirectory,useaoption.HiddenfilesinUnixstartswith.
initsfilename.
$lsa
[rnatarajan@aspdev~]$lsa
.DebianInfo.txt
..CentOSInfo.txt
.bash_historyFedoraInfo.txt
.bash_logout.lftp
.bash_profilelibiconv1.11.tar.tar
.bashrclibssh20.121.2.el4.rf.i386.rpm
Itwillshowallthefilesincludingthe.(currentdirectory)and..(parentdirectory).Toshow
thehiddenfiles,butnotthe.(currentdirectory)and..(parentdirectory),useoptionA.
$lsA
DebianInfo.txtFedoraInfo.txt
CentOSInfo.txtRedHatInfo.txt
.bash_historySUSEInfo.txt
.bash_logout.lftp
.bash_profilelibiconv1.11.tar.tar
.bashrclibssh20.121.2.el4.rf.i386.rpm
[Note:.and..arenotdisplayedhere]
DisplayFilesRecursivelyUsinglsR
$ls/etc/sysconfig/networking
devicesprofiles
$lsR/etc/sysconfig/networking
/etc/sysconfig/networking:
devicesprofiles
/etc/sysconfig/networking/devices:
/etc/sysconfig/networking/profiles:
default
/etc/sysconfig/networking/profiles/default:
Toshowallthefilesrecursively,useRoption.Whenyoudothisfrom/,itshowsallthe
unhiddenfilesinthewholefilesystemrecursively.
DisplayFileInodeNumberUsinglsi
Sometimesyoumaywanttoknowtheinonenumberofafileforinternalmaintenance.Usei
optionasshownbelowtodisplayinonenumber.Usinginodenumberyoucanremovefilesthat
hasspecialcharactersinitsnameasexplainedintheexample#6ofthefindcommandarticle.
$lsi/etc/xinetd.d/
279694chargen279724cupslpd279697daytimeudp
279695chargenudp279696daytime279698echo
HideControlCharactersUsinglsq
Toprintquestionmarkinsteadofthenongraphicscontrolcharactersusetheqoption.
lsq
DisplayFileUIDandGIDUsinglsn
Liststheoutputlikel,butshowstheuidandgidinnumericformatinsteadofnames.
$lsl~/.bash_profile
rwrr1rameshramesh909Feb811:48/home/ramesh/.bash_profile
$lsn~/.bash_profile
rwrr1511511909Feb811:48/home/ramesh/.bash_profile
[Note:Thisdisplay511foruidand511forgid]
VisualClassificationofFilesWithSpecialCharactersUsinglsF
Insteadofdoingthelslandthenthecheckingforthefirstcharactertodeterminethetypeof
file.YoucanuseFwhichclassifiesthefilewithdifferentspecialcharacterfordifferentkindof
files.
$lsF
Desktop/Documents/UbuntuApp@firstfileMusic/Public/Templates/
Thusintheaboveoutput,
/directory.
nothingnormalfile.
@linkfile.
*Executablefile
VisualClassificationofFilesWithColorsUsinglsF
Recognizingthefiletypebythecolorinwhichitgetsdisplayedisananotherkindin
classificationoffile.Intheaboveoutputdirectoriesgetdisplayedinblue,softlinksget
displayedingreen,andordinaryfilesgetsdisplayedindefaultcolor.
$lscolor=auto
DesktopDocumentsExamplesfirstfileMusicPicturesPublicTemplatesVideos
UsefullsCommandAliases
Youcantakesomerequiredlsoptionsintheabove,andmakeitasaliases.Wesuggestthe
following.
Longlistthefilewithsizeinhumanunderstandableform.
aliasll="lslh"
Classifythefiletypebyappendingspecialcharacters.
aliaslv="lsF"
Classifythefiletypebybothcolorandspecialcharacter.
aliasls="lsFcolor=auto"
cd command examples
Thecdcommandsetsthecurrentworkingdirectoryofaprocess.Theusermusthaveexecute
(search)permissioninthespecifieddirectory.
Tochangethecurrentworkingdirectorytothelogin(home)directory
cd
Tochangetoanarbitrarydirectory
cd/usr/include
Thischangesthecurrentdirectoryto/usr/include.
Togodownonelevelofthedirectorytree
cdsys
Ifthecurrentdirectoryis/usr/includeanditcontainsasubdirectorynamedsys,then/
usr/include/sysbecomesthecurrentdirectory.
Togouponelevelofthedirectorytree
cd..
Thespecialfilename,..(dotdot),referstothedirectoryimmediatelyabovethecurrent
directory.
Usecdtotogglebetweenthelasttwodirectories
Useshoptscdspelltoautomaticallycorrectmistypeddirectorynamesoncd
Usecdaliastonavigateupthedirectoryeffectively
Whenyouarenavigatingupaverylongdirectorystructure,youmaybeusingcd..\..\with
multiple..\sdependingonhowmanydirectoriesyouwanttogoupasshownbelow.
#mkdirp/tmp/very/long/directory/structure/that/is/too/deep
#cd/tmp/very/long/directory/structure/that/is/too/deep
#pwd
/tmp/very/long/directory/structure/that/is/too/deep
#cd../../../../
#pwd
/tmp/very/long/directory/structure
Insteadofexecutingcd../../../..tonavigatefourlevelsup,useoneofthefollowingalias
methods:
Navigateupthedirectoryusing..n:Intheexamplebelow,..4isusedtogoup4directory
level,..3togoup3directorylevel,..2togoup2directorylevel.Addthefollowingaliasto
the.bash_profileandrelogin.
alias..="cd.."
alias..2="cd../.."
alias..3="cd../../.."
alias..4="cd../../../.."
alias..5="cd../../../../.."
#cd/tmp/very/long/directory/structure/that/is/too/deep
#..4
[Note:use..4togoup4directorylevel]
#pwd
/tmp/very/long/directory/structure/
Navigateupthedirectoryusingonlydots:Intheexamplebelow,..(fivedots)isusedto
goup4directorylevel.Typing5dotstogoup4directorystructureisreallyeasytoremember,
aswhenyoutypethefirsttwodots,youarethinkinggoinguponedirectory,afterthatevery
additionaldot,istogoonelevelup.So,use.(fourdots)togoup3directoryleveland..
(twodots)togoup1directorylevel.Addthefollowingaliastothe.bash_profileandrelogin
forthe..(fivedots)toworkproperly.
alias..="cd.."
alias...="cd../.."
alias....="cd../../.."
alias.....="cd../../../.."
alias......="cd../../../../.."
#cd/tmp/very/long/directory/structure/that/is/too/deep
#.....
[Note:use.....(fivedots)togoup4directorylevel]
#pwd
/tmp/very/long/directory/structure/
Navigateupthedirectoryusingcdfollowedbyconsecutivedots:Intheexamplebelow,
cd..(cdfollowedbyfivedots)isusedtogoup4directorylevel.Makingit5dotstogoup4
directorystructureisreallyeasytoremember,aswhenyoutypethefirsttwodots,youare
thinkinggoinguponedirectory,afterthateveryadditionaldot,istogoonelevelup.So,use
cd.(cdfollowedbyfourdots)togoup3directorylevelandcd(cdfollowedbythree
dots)togoup2directorylevel.Addthefollowingaliastothe.bash_profileandreloginfor
theabovecd..(fivedots)toworkproperly.
aliascd..="cd.."
aliascd...="cd../.."
aliascd....="cd../../.."
aliascd.....="cd../../../.."
aliascd......="cd../../../../.."
#cd/tmp/very/long/directory/structure/that/is/too/deep
#cd.....
[Note:usecd.....togoup4directorylevel]
#pwd
/tmp/very/long/directory/structure
Performmkdirandcdusingasinglecommand
Sometimeswhenyoucreateanewdirectory,youmaycdtothenewdirectoryimmediatelyto
performsomeworkasshownbelow.
#mkdirp/tmp/subdir1/subdir2/subdir3
#cd/tmp/subdir1/subdir2/subdir3
#pwd
/tmp/subdir1/subdir2/subdir3
Wouldntitbenicetocombinebothmkdirandcdinasinglecommand?Addthefollowingto
the.bash_profileandrelogin.
functionmkdircd(){mkdirp"$@"&&evalcd"\"\$$#\"";}
Now,performbothmkdirandcdatthesametimeusingasinglecommandasshownbelow:
#mkdircd/tmp/subdir1/subdir2/subdir3
[Note:Thiscreatesthedirectoryandcdtoitautomatically]
#pwd
/tmp/subdir1/subdir2/subdir3
Usecdtotogglebetweenthelasttwodirectories
Youcantogglebetweenthelasttwocurrentdirectoriesusingcdasshownbelow.
#cd/tmp/very/long/directory/structure/that/is/too/deep
#cd/tmp/subdir1/subdir2/subdir3
#cd
#pwd
/tmp/very/long/directory/structure/that/is/too/deep
#cd
#pwd
/tmp/subdir1/subdir2/subdir3
#cd
#pwd
/tmp/very/long/directory/structure/that/is/too/deep
pwd command
pwdisPresentworkingdirectory.Whatelsecanbesaidaboutthegoodoldpwdwhohasbeen
printingthecurrentdirectorynameforages.
man command
Displaythemanpageofaspecificcommand.
$mancrontab
Whenamanpageforacommandislocatedundermorethanonesection,youcanviewthe
manpageforthatcommandfromaspecificsectionasshownbelow.
$manSECTIONNUMBERcommandname
Following8sectionsareavailableinthemanpage.
1.
2.
3.
4.
5.
6.
7.
8.
Generalcommands
Systemcalls
Clibraryfunctions
Specialfiles(usuallydevices,thosefoundin/dev)anddrivers
Fileformatsandconventions
Gamesandscreensavers
Miscellaneous
Systemadministrationcommandsanddaemons
Forexample,whenyoudowhatiscrontab,youllnoticethatcrontabhastwomanpages
(section1andsection5).Toviewsection5ofcrontabmanpage,dothefollowing.
$whatiscrontab
crontab(1)maintaincrontabfilesforindividualusers(V3)
crontab(5)tablesfordrivingcron
$man5crontab
whichcommand
Tofindoutifacommandnameislocatedinyourcommandpath:
whichue
/usr/local/bin/ue
ThisreturnstheinformationthattheMicroEMACSeditor(ue)isavailableonthissystemas
thefile/usr/local/bin/ue.
TofindoutiftheKornshellisavailableonyoursystem:
whichksh
/bin/ksh
ThisreturnstheinformationthattheKornshellisavailableonyoursysteminthedirectory
/bin.
Tofindoutwhich(ifany)ofseveralcommandsareavailable:
whichdeletetalkps
Nodeletein/usr/local/utils/bin:/bin:/usr/bin:
/usr/local/ucb/bin:/usr/local/gnu/bin:
/usr/local/public/bin:/usr/bin/X11:.
/usr/bin/talk
/bin/ps
Thisreturnstheinformationthatthefileforthecommanddeletedoesnotexistinanyofthe
directoriesthatarespecifiedinthisuser'sPATHenvironmentvariable.
Pathnamesforthefilesofthecommandstalkandpsaredisplayed,sothesecommandsare
availableonthissystem.
whereis command
WhenyouwanttofindoutwhereaspecificUnixcommandexists(forexample,wheredoesls
commandexists?),youcanexecutethefollowingcommand.
$whereisls
ls:/bin/ls/usr/share/man/man1/ls.1.gz/usr/share/man/man1p/ls.1p.gz
Whenyouwanttosearchanexecutablefromapathotherthanthewhereisdefaultpath,you
canuseBoptionandgivepathasargumenttoit.Thissearchesfortheexecutablelsmkin
the/tmpdirectory,anddisplaysit,ifitisavailable.
$whereisuB/tmpflsmk
lsmk:/tmp/lsmk
whatis command
Whatiscommanddisplaysasinglelinedescriptionaboutacommand.
$whatisls
ls(1)listdirectorycontents
$whatisifconfig
ifconfig(8)configureanetworkinterface
unamecommand
UnamecommanddisplaysimportantinformationaboutthesystemsuchasKernelname,
Hostname,Kernelreleasenumber,
Processortype,etc.,
SampleunameoutputfromaUbuntulaptopisshownbelow.
$unamea
Linuxjohnlaptop2.6.3224generic#41UbuntuSMPThuAug1901:12:52UTC2010i686GNU/Linux
mkdir command
ThemkdircommandcreatesoneormorenewdirectoriesspecifiedbytheDirectoryparameter.
Eachnewdirectorycontainsthestandardentries.(dot)and..(dotdot).Youcanspecifythe
permissionsforthenewdirectorieswiththemModeflag.Youcanusetheumasksubroutine
tosetthedefaultmodeforthemkdircommand.
TheownerIDandgroupIDofthenewdirectoriesaresettotheprocess'seffectiveuserIDand
groupID,respectively.Thesetgidbitsettingisinheritedfromtheparentdirectory.Tochange
thesetgidbit,youcaneitherspecifythemModeflagorissuethechmodcommandafterthe
creationofthedirectory.
Note:Tomakeanewdirectoryyoumusthavewritepermissionintheparent
directory.
Flags
eCreatesdirectorieswithencryptioninheritance.
mModeSetsthepermissionbitsforthenewlycreateddirectoriestothevaluespecifiedby
theModevariable.TheModevariabletakesthesamevaluesastheModeparameterforthe
chmodcommand,eitherinsymbolicornumericform.
Whenyouspecifythemflagusingsymbolicformat,theopcharacters+(plus)and(minus)
areinterpretedrelativetotheassumedpermissionsettinga=rwx.The+addspermissionsto
thedefaultmode,andthedeletespermissionsfromthedefaultmode.Refertothechmod
commandforacompletedescriptionofpermissionbitsandformats.
pCreatesmissingintermediatepathnamedirectories.Ifthepflagisnotspecified,theparent
directoryofeachnewlycreateddirectorymustalreadyexist.
Intermediatedirectoriesarecreatedthroughtheautomaticinvocationofthefollowingmkdir
commands:
mkdirpm$(umaskS),u+wx$(dirnameDirectory)&&
mkdir[mMode]Directory
wherethe[mMode]representsanyoptionsuppliedwithyouroriginalinvocationofthe
mkdircommand.
ThemkdircommandignoresanyDirectoryparameterthatnamesanexistingdirectory.No
errorisissued.
Tocreateanewdirectoryinthecurrentworkingdirectory,
mkdirTest
TheTestdirectoryiscreatedwithdefaultpermissions.
Tocreateanewdirectorywithpermissions
TocreateanewdirectorycalledTestwithrwxrxrxpermissionsinthepreviouslycreated
/home/demo/sub1directory
mkdirm755/home/demo/sub1/Test
Tocreateanewdirectorywithdefaultpermissionsinsubdirectory
TocreateanewdirectorycalledTestwithdefaultpermissionsinthe/home/demo/sub2
directory
mkdirp/home/demo/sub2/Test
Thepflagcreatesthe/home,/home/demo,and/home/demo/sub2directoriesiftheydonot
alreadyexist.
rmdir command
Toemptyandremoveadirectory
rmmydir/*mydir/.*
rmdirmydir
Thiscommandremovesthecontentsofthemydirfileandthenremovestheemptydirectory.
Thermcommanddisplaysanerrormessageabouttryingtoremovethedirectories.(dot)and
..(dot,dot),andthenthermdircommandremovesthem.
Notethatthermmydir/*mydir/.*commandfirstremovesfileswithnamesthatdonotbegin
withadot,andthenremovesthosewithnamesthatdobeginwithadot.Youmaynotrealize
thatthedirectorycontainsfilenamesthatbeginwithadotbecausethelscommanddoesnot
usuallylistthemunlessyouusetheaflag.
Toremovethesubdirectory
Toremovethe/home,/home/demo,and/home/demo/mydirdirectories,type:
rmdirp/home/demo/mydir
Thiscommandremovesfirstthe/mydirdirectoryandthenthe/demoand/homedirectories,
respectively.Ifadirectoryisnotemptyordoesnothavewritepermissionwhenitistobe
removed,thecommandterminates.
touch command
Thetouchcommandupdatestheaccessandmodificationtimesofeachfilespecifiedbythe
FileparameterofeachdirectoryspecifiedbytheDirectoryparameter.Ifyoudonotspecifya
valuefortheTimevariable,thetouchcommandusesthecurrenttime.Ifyouspecifyafilethat
doesnotexist,thetouchcommandcreatesthefileunlessyouspecifythecflag.
Thereturncodefromthetouchcommandisthenumberoffilesforwhichthetimescouldnot
besuccessfullymodified(includingfilesthatdidnotexistandwerenotcreated).
aChangestheaccesstimeofthefilespecifiedbytheFilevariable.Doesnotchangethe
modificationtimeunlessmisalsospecified.cDoesnotcreatethefileifitdoesnotalready
exist.Nodiagnosticmessagesarewrittenconcerningthiscondition.fAttemptstoforcethe
touchinspiteofreadandwritepermissionsonafile.mChangesthemodificationtimeofFile.
Doesnotchangetheaccesstimeunlessaisalsospecified.rRefFileUsesthecorresponding
timeofthefilespecifiedbytheRefFilevariableinsteadofthecurrenttime.TimeSpecifiesthe
dateandtimeofthenewtimestampintheformatMMDDhhmm[YY],where:
MM
DD
Specifiesthemonthoftheyear(01to12).
Specifiesthedayofthemonth(01to31).
hh
mm
YY
Specifiesthehouroftheday(00to23).
Specifiestheminuteofthehour(00to59).
Specifiesthelasttwodigitsoftheyear.IftheYYvariableisnotspecified,thedefault
valueisthecurrentyear.
tTimeUsesthespecifiedtimeinsteadofthecurrenttime.TheTimevariableisspecifiedinthe
decimalform[[CC]YY]MMDDhhmm[.SS]where:
CC
Specifiesthefirsttwodigitsoftheyear.
YY
MM
Specifiesthemonthoftheyear(01to12).
DD
Specifiesthedayofthemonth(01to31).
hh
mm
SS
Specifiesthelasttwodigitsoftheyear.
Specifiesthehouroftheday(00to23).
Specifiestheminuteofthehour(00to59).
Specifiesthesecondoftheminute(00to59).
Toupdatetheaccessandmodificationtimesofafile,
touchprogram.c
Thissetsthelastaccessandmodificationtimesoftheprogram.cfiletothecurrentdateand
time.Iftheprogram.cfiledoesnotexist,thetouchcommandcreatesanemptyfilewiththat
name.
Toavoidcreatinganewfile
touchc
program.c
Toupdateonlythemodificationtime,enter:
touchm*.o
Thisupdatesthelastmodificationtimes(nottheaccesstimes)ofthefilesthatendwitha.o
extensioninthecurrentdirectory.Thetouchcommandisoftenusedinthiswaytoalterthe
resultsofthemakecommand.
Toexplicitlysettheaccessandmodificationtimes
touchc
t
02171425program.c
Thissetstheaccessandmodificationdatesto14:25(2:25p.m.)February17ofthecurrent
year.
Tousethetimestampofanotherfileinsteadofthecurrenttime
touchr
file1program.c
Thisgivestheprogram.cfilethesametimestampasthefile1file.
Totouchafileusingaspecifiedtimeotherthanthecurrenttime
toucht
198503030303.55program.c
Thisgivestheprogram.cfileatimestampof3:03:55a.m.onMarch3,1985.
rm command
Todeleteafile
rmmyfile
Ifthereisanotherlinktothisfile,thenthefileremainsunderthatname,butthenamemyfile
isremoved.Ifmyfileistheonlylink,thefileitselfisdeleted.
Todeleteafilewithoutfirstreceivingaconfirmationprompt
rmf
core
Noconfirmationpromptisissuedbeforethermfcommandattemptstoremovethefile
namedcore.However,anerrormessagedisplaysifthecorefileiswriteprotectedandyouare
nottheownerofthefileoryoudonothaverootauthority.Noerrormessagedisplayswhen
thermfcommandattemptstoremovenonexistentfiles.
Todeletefilesonebyone
rmi
mydir/*
Aftereachfilenameisdisplayed,enterytodeletethefile,orpresstheEnterkeytokeepit.
Todeleteadirectorytree,enter:
rmirmanual
Thiscommandrecursivelyremovesthecontentsofallsubdirectoriesofthemanualdirectory,
promptingyouregardingtheremovalofeachfile,andthenremovesthemanualdirectory
itself,forexample:
You:rmirmanual
System:rm:Selectfilesindirectorymanual?Enteryforyes.
You:y
System:rm:Selectfilesindirectorymanual/draft1?Enteryforyes.
You:y
System:rm:Removemanual/draft1?
You:y
System:rm:Removemanual/draft1/chapter1?
You:y
System:rm:Removemanual/draft1/chapter2?
You:y
System:rm:Selectfilesindirectorymanual/draft2?Enteryforyes.
You:y
System:rm:Removemanual/draft2?
You:y
System:rm:Removemanual?
You:y
Here,thermcommandfirstasksifyouwantittosearchthemanualdirectory.Becausethe
manualdirectorycontainsdirectories,thermcommandnextasksforpermissiontosearch
manual/draft1forfilestodelete,andthenasksifyouwantittodeletethe
manual/draft1/chapter1andmanual/draft1/chapter2files.Thermcommandnextasksfor
permissiontosearchthemanual/draft2directory.Thenasksforpermissiontodeletethe
manual/draft1,manual/draft2,andmanualdirectories.
Ifyoudenypermissiontoremoveasubdirectory(forexample,manual/draft2),therm
commanddoesnotremovethemanualdirectory.Instead,youseethemessage:rm:Directory
manualnotempty.
cp command
Copyfile1tofile2preservingthemode,ownershipandtimestamp.
$cppfile1file2
Copyfile1tofile2.iffile2existspromptforconfirmationbeforeoverwrittingit.
$cpifile1file2
Tomakeacopyofafileinthecurrentdirectory,
cpprog.cprog.bak
Thiscopiesprog.ctoprog.bak.Iftheprog.bakfiledoesnotalreadyexist,thecpcommand
createsit.Ifitdoesexist,thecpcommandreplacesitwithacopyoftheprog.cfile.
Tocopyafileinyourcurrentdirectoryintoanotherdirectory,
cpjones/home/nick/clients
Thiscopiesthejonesfileto/home/nick/clients/jones.
Tocopyafiletoanewfileandpreservethemodificationdate,time,andaccesscontrol
listassociatedwiththesourcefile
cpp
smithsmith.jr
Thiscopiesthesmithfiletothesmith.jrfile.Insteadofcreatingthefilewiththecurrentdate
andtimestamp,thesystemgivesthesmith.jrfilethesamedateandtimeasthesmithfile.The
smith.jrfilealsoinheritsthesmithfile'saccesscontrolprotection.
Tocopyallthefilesinadirectorytoanewdirectory,
cp/home/janet/clients/*/home/nick/customers
Thiscopiesonlythefilesintheclientsdirectorytothecustomersdirectory.
Tocopyadirectory,includingallitsfilesandsubdirectories,toanotherdirectory
cpR
/home/nick/clients/home/nick/customers
Note:Adirectorycannotbecopiedintoitself.Thiscopiestheclientsdirectory,includingallits
files,subdirectories,andthefilesinthosesubdirectories,tothecustomers/clientsdirectory.
Tocopyaspecificsetoffilestoanotherdirectory
cpjoneslewissmith/home/nick/clients
Thiscopiesthejones,lewis,andsmithfilesinyourcurrentworkingdirectorytothe
/home/nick/clientsdirectory.
Tousepatternmatchingcharacterstocopyfiles,
cpprograms/*.c.
Thiscopiesthefilesintheprogramsdirectorythatendwith.ctothecurrentdirectory,
signifiedbythesingle.(dot).Youmusttypeaspacebetweenthecandthefinaldot.
TocopyafiletoanewfileandpreservetheACLandEAassociatedwiththesourcefile,
cpUsmithsmith.jr
mv command
Renameafile
Renamefile1tofile2.iffile2existspromptforconfirmationbeforeoverwrittingit.
$mvifile1file2
$mv/home/dir/file1/home/dir/file2
mvfisjusttheopposite,whichwilloverwritefile2withoutprompting.
Thiscommandrenamesfile1tofile2.Ifafilenamedfile2alreadyexists,itsoldcontentsare
replacedwiththoseofappendix.
mvvwillprintwhatishappeningduringfilerename,whichisusefulwhilespecifyingshell
metacharactersinthefilenameargument.
$mvvfile1file2
Tomoveadirectory
mvbookmanual
Thiscommandmovesallfilesanddirectoriesunderbooktothedirectorynamedmanual,if
manualexists.Otherwise,thedirectorybookisrenamedmanual.
Tomoveafiletoanotherdirectoryandgiveitanewname
mvintromanual/chap1
Thiscommandmovesintrotomanual/chap1.Thenameintroisremovedfromthe
currentdirectory,andthesamefileappearsaschap1inthedirectorymanual.
Tomoveafiletoanotherdirectory,keepingthesamename
mvchap3manual
Thiscommandmoveschap3tomanual/chap3
Note:Examples1and3nametwofiles,example2namestwoexisting
directories,andexample4namesafileandadirectory.
Tomoveseveralfilesintoanotherdirectory
mvchap4jim/chap5/home/manual
Thiscommandmovesthechap4filetothe/home/manual/chap4filedirectoryandthe
jim/chap5filetothe/home/manual/chap5file.
Tousethemvcommandwithpatternmatchingcharacters
mvmanual/*.
Thiscommandmovesallfilesinthemanualdirectoryintothecurrentdirectory.
(period),retainingthenamestheyhadinmanual.Thismovealsoemptiesmanual.You
musttypeaspacebetweentheasteriskandtheperiod.
Note:Patternmatchingcharactersexpandnamesofexistingfilesonly.For
example,thecommandmvintroman*/chap1doesnotworkifthefile
manual/chap1doesnotexist.
cat command
Todisplayafileattheworkstation
catnotes
Thiscommanddisplaysthedatainthenotesfile.Ifthefileismorethanonelessthan
thenumberofavailabledisplaylines,someofthefilescrollsoffthescreen.Tolistafile
onepageatatime,usethepgcommand.
Toconcatenateseveralfiles
catsection1.1section1.2section1.3>section1
Thiscommandcreatesafilenamedsection1thatisacopyofsection1.1followedby
section1.2andsection1.3.
Tosuppresserrormessagesaboutfilesthatdonotexist
catq
section2.1section2.2section2.3>section2
Ifsection2.1doesnotexist,thiscommandconcatenatessection2.2andsection2.3.The
resultisthesameifyoudonotusetheqflag,exceptthatthecatcommanddisplays
theerrormessage:
cat:cannotopensection2.1
Youmaywanttosuppressthismessagewiththeqflagwhenyouusethecatcommand
inshellprocedures.
Toappendonefiletotheendofanother,
catsection1.4>>section1
The>>(twocarets)appendsacopyofsection1.4totheendofsection1.Ifyouwantto
replacethefile,usethe>(caret).
Toaddtexttotheendofafile
cat>>notes
Getmilkonthewayhome
CtrlD
ThiscommandaddsGetmilkonthewayhometotheendofthefilecallednotes.The
catcommanddoesnotprompt;itwaitsforyoutoentertext.PresstheCtrlDkey
sequencetoindicateyouarefinished.
Toconcatenateseveralfileswithtextenteredfromthekeyboard
catsection3.1section3.3>section3
Thiscommandconcatenatesthefilesection3.1withtextfromthekeyboard(indicated
bytheminussign),andthefilesection3.3,thendirectstheoutputintothefilecalled
section3.
Youcanviewmultiplefilesatthesametime.Followingexampleprintsthecontentoffile1
followedbyfile2tostdout.
$catfile1file2
Whiledisplayingthefile,followingcatncommandwillprependthelinenumbertoeachline
oftheoutput.
$catn/etc/logrotate.conf
1/var/log/btmp{
2missingok
3monthly
4create0660rootutmp
5rotate1
6}
headcommand
1.PrintthefirstNnumberoflines
ToviewthefirstNnumberoflines,passthefilenameasanargumentwithnoptionasshown
below.
$headn5flavours.txt
Ubuntu
Debian
Redhat
Gentoo
Fedoracore
Note:Whenyousimplypassthefilenameasanargumenttohead,itprintsoutthefirst10
linesofthefile.
2.PrintNnumberoflinesbyspecifyingNwith
Youdontevenneedtopassthenoptionasanargument,simplyspecifytheNnumberoflines
followedbyasshownbelow.
$head4flavours.txt
Ubuntu
Debian
Redhat
Gentoo
3.PrintallbutnotthelastNlines
Byplacinginfrontofthenumberwithnoption,itprintsallthelinesofeachfilebutnotthe
lastNlinesasshownbelow,
$headn5flavours.txt
Ubuntu
4.PrinttheNnumberofbytes
YoucanusethecoptiontoprinttheNnumberofbytesfromtheinitialpartoffile.
$headc5flavours.txt
Ubuntu
Note:Aslikenoption,herealsoyoucanpassinfrontofnumbertoprintallbytesbutnot
thelastNbytes.
5.PassingOutputofOthercommandtoHeadInput
Youmaypasstheoutputofothercommandstotheheadcommandviapipeasshownbelow,
$ls|head
bin
boot
cdrom
dev
etc
home
initrd.img
lib
lost+found
media
Displaythefirst5linesofseveralfiles
head5*.xdh
Thisdisplays,oneaftertheother,thefirst5linesofeachfilewiththeextension.xdhinthe
currentdirectory.
Thefirstlineofeachfileisshownas:==>filename<==
tailcommand
TailprintsthelastNnumberoflinesfromgiveninput.Bydefault,itprintslast10linesofeach
givenfile.
1.PrintthelastNlines
ToviewthelastNnumberoflinesfromfile,justpassthefilenamewithnoptionasshown
below.
$tailn5flavours.txt
Debian
Redhat
Gentoo
Fedoracore
Note:Whenyousimplypassthefilename,itprintsoutthelast10linesofthefile.
2.Printtheappendedlinesasandwhenthefilegrows
Youcanusefoptiontooutputtheappendedlinesoffileinstantlyasshownbelow,
$tailf/var/log/messages
Note:Thisisveryusefultomonitorthelogfiles.
3.TerminatethetailcommandoncePIDdies
Usingpidwithfoption,youcanterminatethetailcommandwhenthespecificprocessgets
overorkilledasshownbelow.
$tailf/tmp/debug.logpid=2575
Intheabovetailgetsterminatedimmediatelywhenthepid2575vanishes.
4.Keepontryingtotailthefileevenifitisnonexistent
Sometimes,thefileintendedtotailmaynotbeavailablewhenyourunthetailcommandand
itmaygetcreatedlaterorthefilesbecomesinaccessible.Bythistime,youcanusetheretry
optiontokeepontryingtoopenthefileasshownbelow.
$tailf/tmp/debug.logretry
tail:warning:retryisusefulmainlywhenfollowingbyname
tail:cannotopen`/tmp/log'forreading:Nosuchfileordirectory
Aftergivingtheabovewarnings,itistryingtoopenthefile.
lesscommand
ViewingaTextFile:moreorless
Often,youwillwanttolookatatextfile,withoutbotheringtoloaditintoaneditoryoujust
wanttoreadit,perhapsbeforedeletingit,tomakesureitwaswhatyouthoughtitwas.UNIX
providesseveralwaysofdoingthis.Youmayseepeopleusethecommand"cat"butwe'renot
goingtorecommendthatherebecauseofitsrelativeuselessnessforthispurpose.Instead,
we'regoingtogiveyoutwoothercommands,moreorless...
No,really:thosearethecommands;moreandless.Pickeitherone;they'reverysimilar.We'll
discuss"less"here.
Theformatofthecommandis:
lessfilename
Thiswillcausethefiletobedisplayedtoyourscreen,onescreenfullatatime.Thereis
immediatehelpformore,accessibleviathehsubcommand(whenyou're"in"less).Pressing
the<Spacebar>movesyouforwardonescreenthroughthefile.Youcanusethe
subcommandbtomovebackwardonescreen.Whenyou'rereadytoquit,q(for"quit")exits
thefileandreturnsyoutotheUNIX$prompt.
Thereareothercommandstoletyoudothingslikemoveforwardorbackwardahalfscreen,
oraparticularnumberoflinesorscreens.Typeh(inlessormore)toseeacompletelist.
MoreUsesforlessormore
Thelessandmorecommandsarealsousefulforpagingthroughlongoutputofothertypes;
like,forexample,ifyourlslalistingrunsoffthescreen,andyouwanttobeabletoviewit
onescreenfullatatime.
Ingeneral,
command|less
...willinvokelesstohandleoutputsoyoucanpageforwardandbackwardthroughit.For
example,foralongdirectorylisting,
lsla|less
wouldletyouviewthelistingusinglesstocontrolpagingforwardandbackwardsthroughthe
listing.
The|symbol(calledthe"verticalbar,"or"pipe")isfoundas<Shift><backslash>onthe
rightsideofmostkeyboards,abovethe<Enter>key.Basically,itisaUNIXmechanismwhich
allowsyouto"stringtogether"multiplecommands,suchthattheoutputfromeachcommand
isfedtotheinputofthenextcommand,andsoon,allowingyoutocreatemorecomplex
"combinationcommands."Inthecaseoflsla|less,weare"piping"theoutputoflslathrough
less.
tarcommand
a.Creatinganarchiveusingtarcommand
Creatinganuncompressedtararchiveusingoptioncvf
Thisisthebasiccommandtocreateatararchive.
$tarcvfarchive_name.tardirname/
Intheabovecommand:
ccreateanewarchive
vverboselylistfileswhichareprocessed.
ffollowingisthearchivefilename
Creatingatargzippedarchiveusingoptioncvzf
Theabovetarcvfoption,doesnotprovideanycompression.Touseagzipcompressiononthe
tararchive,usethezoptionasshownbelow.
$tarcvzfarchive_name.tar.gzdirname/
zfilterthearchivethroughgzip
Note:.tgzissameas.tar.gz
Note:Iliketokeepthecvf(ortvf,orxvf)optionunchangedforallarchivecreation(orview,
orextract)andaddadditionaloptionattheend,whichiseasiertoremember.i.ecvffor
archivecreation,cvfzforcompressedgziparchivecreation,cvfjforcompressedbzip2archive
creationetc.,Forthismethodtoworkproperly,dontgiveinfrontoftheoptions.
Creatingabzippedtararchiveusingoptioncvjf
Createabzip2tararchiveasshownbelow:
$tarcvfjarchive_name.tar.bz2dirname/
jfilterthearchivethroughbzip2
gzipvsbzip2:bzip2takesmoretimetocompressanddecompressthangzip.bzip2archival
sizeislessthangzip.
Note:.tbzand.tb2issameas.tar.bz2
b.Extracting(untar)anarchiveusingtarcommand
Extracta*.tarfileusingoptionxvf
Extractatarfileusingoptionxasshownbelow:
$tarxvfarchive_name.tar
xextractfilesfromarchive
Extractagzippedtararchive(*.tar.gz)usingoptionxvzf
Usetheoptionzforuncompressingagziptararchive.
$tarxvfzarchive_name.tar.gz
Extractingabzippedtararchive(*.tar.bz2)usingoptionxvjf
Usetheoptionjforuncompressingabzip2tararchive.
$tarxvfjarchive_name.tar.bz2
Note:Inalltheabovecommandsvisoptional,whichliststhefilebeingprocessed.
c.Listinganarchiveusingtarcommand
Viewthetararchivefilecontentwithoutextractingusingoptiontvf
Youcanviewthe*.tarfilecontentbeforeextractingasshownbelow.
$tartvfarchive_name.tar
Viewthe*.tar.gzfilecontentwithoutextractingusingoptiontvzf
Youcanviewthe*.tar.gzfilecontentbeforeextractingasshownbelow.
$tartvfzarchive_name.tar.gz
Viewthe*.tar.bz2filecontentwithoutextractingusingoptiontvjf
Youcanviewthe*.tar.bz2filecontentbeforeextractingasshownbelow.
$tartvfjarchive_name.tar.bz2
d.Listingoutthetarfilecontentwithlesscommand
Whenthenumberoffilesinanarchiveismore,youmaypipetheoutputoftartoless.But,
youcanalsouselesscommanddirectlytoviewthetararchiveoutput.
e.Extractasinglefilefromtar,tar.gz,tar.bz2file
Toextractaspecificfilefromatararchive,specifythefilenameattheendofthetarxvf
commandasshownbelow.Thefollowingcommandextractsonlyaspecificfilefromalargetar
file.
$tarxvfarchive_file.tar/path/to/file
Usetherelevantoptionzorjaccordingtothecompressionmethodgziporbzip2respectively
asshownbelow.
$tarxvfzarchive_file.tar.gz/path/to/file
$tarxvfjarchive_file.tar.bz2/path/to/file
f.Extractasingledirectoryfromtar,tar.gz,tar.bz2file
Toextractasingledirectory(alongwithitssubdirectoryandfiles)fromatararchive,specify
thedirectorynameattheendofthetarxvfcommandasshownbelow.Thefollowingextracts
onlyaspecificdirectoryfromalargetarfile.
$tarxvfarchive_file.tar/path/to/dir/
Toextractmultipledirectoriesfromatararchive,specifythoseindividualdirectorynamesat
theendofthetarxvfcommandasshownbelow.
$tarxvfarchive_file.tar/path/to/dir1//path/to/dir2/
Usetherelevantoptionzorjaccordingtothecompressionmethodgziporbzip2respectively
asshownbelow.
$tarxvfzarchive_file.tar.gz/path/to/dir/
$tarxvfjarchive_file.tar.bz2/path/to/dir/
g.Extractgroupoffilesfromtar,tar.gz,tar.bz2archivesusingregular
expression
Youcanspecifyaregex,toextractfilesmatchingaspecifiedpattern.Forexample,following
tarcommandextractsallthefileswithplextension.
$tarxvfarchive_file.tarwildcards'*.pl'
Optionsexplanation:
wildcards*.plfileswithplextension
h.Addingafileordirectorytoanexistingarchiveusingoptionr
Youcanaddadditionalfilestoanexistingtararchiveasshownbelow.Forexample,toappend
afileto*.tarfiledothefollowing:
$tarrvfarchive_name.tarnewfile
Thisnewfilewillbeaddedtotheexistingarchive_name.tar.Addingadirectorytothetaris
alsosimilar,
$tarrvfarchive_name.tarnewdir/
Note:Youcannotaddfileordirectorytoacompressedarchive.Ifyoutrytodoso,youwillget
tar:Cannotupdatecompressedarchiveserrorasshownbelow.
$tarrvfzarchive_name.tgznewfile
tar:Cannotupdatecompressedarchives
Try`tarhelp'or`tarusage'formoreinformation.
i.VerifyfilesavailableintarusingoptionW
Aspartofcreatingatarfile,youcanverifythearchivefilethatgotcreatedusingtheoptionW
asshownbelow.
$tarcvfWfile_name.tardir/
Ifyouareplanningtoremoveadirectory/filefromanarchivefileorfromthefilesystem,you
mightwanttoverifythearchivefilebeforedoingitasshownbelow.
$tartvfWfile_name.tar
Verify1/file1
1/file1:Modtimediffers
1/file1:Sizediffers
Verify1/file2
Verify1/file3
IfanoutputlinestartswithVerify,andthereisnodifferslinethenthefile/directoryisOk.If
not,youshouldinvestigatetheissue.
Note:foracompressedarchivefile(*.tar.gz,*.tar.bz2)youcannotdotheverification.
Findingthedifferencebetweenanarchiveandfilesystemcanbedoneevenforacompressed
archive.ItalsoshowsthesameoutputasaboveexcludingthelineswithVerify.
Findingthedifferencebetweengziparchivefileandfilesystem
$tardfzfile_name.tgz
Findingthedifferencebetweenbzip2archivefileandfilesystem
$tardfjfile_name.tar.bz2
j.Estimatethetararchivesize
Thefollowingcommand,estimatesthetarfilesize(inKB)beforeyoucreatethetarfile.
$tarcf/directory/to/archive/|wcc
20480
Thefollowingcommand,estimatesthecompressedtarfilesize(inKB)beforeyoucreatethe
tar.gz,tar.bz2files.
$tarczf/directory/to/archive/|wcc
508
$tarcjf/directory/to/archive/|wcc
428
locate command
Usinglocatecommandyoucanquicklysearchforthelocationofaspecificfile(orgroupof
files).Locatecommandusesthedatabasecreatedbyupdatedb.
Theexamplebelowshowsallfilesinthesystemthatcontainsthewordcrontabinit.
$locatecrontab
/etc/anacrontab
/etc/crontab
/usr/bin/crontab
/usr/share/doc/cron/examples/crontab2english.pl.gz
/usr/share/man/man1/crontab.1.gz
/usr/share/man/man5/anacrontab.5.gz
/usr/share/man/man5/crontab.5.gz
/usr/share/vim/vim72/syntax/crontab.vim
grepcommandexamples
a.Searchforthegivenstringinasinglefile
Thebasicusageofgrepcommandistosearchforaspecificstringinthespecifiedfileasshown
below.
Syntax:grep"literal_string"filename
$grep"this"demo_file
thislineisthe1stlowercaselineinthisfile.
Twolinesabovethislineisempty.
b.Checkingforthegivenstringinmultiplefiles.
Syntax:grep"string"FILE_PATTERN
Thisisalsoabasicusageofgrepcommand.Forthisexample,letuscopythedemo_fileto
demo_file1.Thegrepoutputwillalsoincludethefilenameinfrontofthelinethatmatched
thespecificpatternasshownbelow.WhentheLinuxshellseesthemetacharacter,itdoesthe
expansionandgivesallthefilesasinputtogrep.
$cpdemo_filedemo_file1
$grep"this"demo_*
demo_file:thislineisthe1stlowercaselineinthisfile.
demo_file:Twolinesabovethislineisempty.
demo_file:Andthisisthelastline.
demo_file1:thislineisthe1stlowercaselineinthisfile.
demo_file1:Twolinesabovethislineisempty.
demo_file1:Andthisisthelastline.
c.Caseinsensitivesearchusinggrepi
Syntax:grepi"string"FILE
Thisisalsoabasicusageofthegrep.Thissearchesforthegivenstring/patterncase
insensitively.Soitmatchesallthewordssuchasthe,THEandThecaseinsensitivelyas
shownbelow.
$grepi"the"demo_file
THISLINEISTHE1STUPPERCASELINEINTHISFILE.
thislineisthe1stlowercaselineinthisfile.
ThisLineHasAllItsFirstCharacterOfTheWordWithUpperCase.
Andthisisthelastline.
d.Matchregularexpressioninfiles
Syntax:grep"REGEX"filename
Thisisaverypowerfulfeature,ifyoucanuseuseregularexpressioneffectively.Inthe
followingexample,itsearchesforallthepatternthatstartswithlinesandendswithempty
withanythinginbetween.i.eTosearchlines[anythinginbetween]emptyinthedemo_file.
$grep"lines.*empty"demo_file
Twolinesabovethislineisempty.
Fromdocumentationofgrep:Aregularexpressionmaybefollowedbyoneofseveral
repetitionoperators:
?Theprecedingitemisoptionalandmatchedatmostonce.
*Theprecedingitemwillbematchedzeroormoretimes.
+Theprecedingitemwillbematchedoneormoretimes.
{n}Theprecedingitemismatchedexactlyntimes.
{n,}Theprecedingitemismatchednormoretimes.
{,m}Theprecedingitemismatchedatmostmtimes.
{n,m}Theprecedingitemismatchedatleastntimes,butnotmorethanmtimes.
e.Checkingforfullwords,notforsubstringsusinggrepw
Ifyouwanttosearchforaword,andtoavoidittomatchthesubstringsusewoption.Just
doingoutanormalsearchwillshowoutallthelines.
Thefollowingexampleistheregulargrepwhereitissearchingforis.Whenyousearchfor
is,withoutanyoptionitwillshowoutis,his,thisandeverythingwhichhasthe
substringis.
$grepi"is"demo_file
THISLINEISTHE1STUPPERCASELINEINTHISFILE.
thislineisthe1stlowercaselineinthisfile.
ThisLineHasAllItsFirstCharacterOfTheWordWithUpperCase.
Twolinesabovethislineisempty.
Andthisisthelastline.
ThefollowingexampleistheWORDgrepwhereitissearchingonlyforthewordis.Please
notethatthisoutputdoesnotcontainthelineThisLineHasAllItsFirstCharacterOfThe
WordWithUpperCase,eventhoughisisthereintheThis,asthefollowingislookingonly
forthewordisandnotforthis.
$grepiw"is"demo_file
THISLINEISTHE1STUPPERCASELINEINTHISFILE.
thislineisthe1stlowercaselineinthisfile.
Twolinesabovethislineisempty.
Andthisisthelastline.
f.Displayinglinesbefore/after/aroundthematchusinggrepA,BandC
Whendoingagreponahugefile,itmaybeusefultoseesomelinesafterthematch.You
mightfeelhandyifgrepcanshowyounotonlythematchinglinesbutalsothelines
after/before/aroundthematch.
Pleasecreatethefollowingdemo_textfileforthisexample.
$catdemo_text
4.VimWordNavigation
Youmaywanttodoseveralnavigationinrelationtothewords,suchas:
*egototheendofthecurrentword.
*EgototheendofthecurrentWORD.
*bgototheprevious(before)word.
*Bgototheprevious(before)WORD.
*wgotothenextword.
*WgotothenextWORD.
WORDWORDconsistsofasequenceofnonblankcharacters,separatedwithwhitespace.
wordwordconsistsofasequenceofletters,digitsandunderscores.
ExampletoshowthedifferencebetweenWORDandword
*192.168.1.1singleWORD
*192.168.1.1sevenwords.
f.1DisplayNlinesaftermatch
AistheoptionwhichprintsthespecifiedNlinesafterthematchasshownbelow.
Syntax:
grepA<N>"string"FILENAME
Thefollowingexampleprintsthematchedline,alongwiththe3linesafterit.
$grepA3i"example"demo_text
ExampletoshowthedifferencebetweenWORDandword
*192.168.1.1singleWORD
*192.168.1.1sevenwords.
f.2DisplayNlinesbeforematch
BistheoptionwhichprintsthespecifiedNlinesbeforethematch.
Syntax:
grepB<N>"string"FILENAME
WhenyouhadoptiontoshowtheNlinesaftermatch,youhavetheBoptionfortheopposite.
$grepB2"singleWORD"demo_text
ExampletoshowthedifferencebetweenWORDandword
*192.168.1.1singleWORD
f.3DisplayNlinesaroundmatch
CistheoptionwhichprintsthespecifiedNlinesbeforethematch.Insomeoccasionyou
mightwantthematchtobeappearedwiththelinesfromboththeside.ThisoptionsshowsN
linesinboththeside(before&after)ofmatch.
$grepC2"Example"demo_text
wordwordconsistsofasequenceofletters,digitsandunderscores.
ExampletoshowthedifferencebetweenWORDandword
*192.168.1.1singleWORD
g.HighlightingthesearchusingGREP_OPTIONS
Asgrepprintsoutlinesfromthefilebythepattern/stringyouhadgiven,ifyouwanteditto
highlightwhichpartmatchestheline,thenyouneedtofollowthefollowingway.
Whenyoudothefollowingexportyouwillgetthehighlightingofthematchedsearches.Inthe
followingexample,itwillhighlightallthethiswhenyousettheGREP_OPTIONSenvironment
variableasshownbelow.
$exportGREP_OPTIONS='color=auto'GREP_COLOR='100;8'
$grepthisdemo_file
thislineisthe1stlowercaselineinthisfile.
Twolinesabovethislineisempty.
Andthisisthelastline.
h.Searchinginallfilesrecursivelyusinggrepr
Whenyouwanttosearchinallthefilesunderthecurrentdirectoryanditssubdirectory.r
optionistheonewhichyouneedtouse.Thefollowingexamplewilllookforthestring
rameshinallthefilesinthecurrentdirectoryandallitssubdirectory.
$grepr"ramesh"*
i.Invertmatchusinggrepv
Youhaddifferentoptionstoshowthelinesmatched,toshowthelinesbeforematch,andto
showthelinesaftermatch,andtohighlightmatch.SodefinitelyYoudalsowanttheoptionv
todoinvertmatch.
Whenyouwanttodisplaythelineswhichdoesnotmatchesthegivenstring/pattern,usethe
optionvasshownbelow.Thisexamplewilldisplayallthelinesthatdidnotmatchtheword
go.
$grepv"go"demo_text
4.VimWordNavigation
Youmaywanttodoseveralnavigationinrelationtothewords,suchas:
WORDWORDconsistsofasequenceofnonblankcharacters,separatedwithwhitespace.
wordwordconsistsofasequenceofletters,digitsandunderscores.
ExampletoshowthedifferencebetweenWORDandword
*192.168.1.1singleWORD
*192.168.1.1sevenwords.
j.displaythelineswhichdoesnotmatchesallthegivenpattern.
Syntax:
grepve"pattern"e"pattern"
$cattestfile.txt
a
b
c
d
$grepve"a"e"b"e"c"testfile.txt
d
k.Countingthenumberofmatchesusinggrepc
Whenyouwanttocountthathowmanylinesmatchesthegivenpattern/string,thenusethe
optionc.
Syntax:
grepc"pattern"filename
$grepc"go"demo_text
6
Whenyouwantdofindouthowmanylinesmatchesthepattern
$grepcthisdemo_file
3
Whenyouwantdofindouthowmanylinesthatdoesnotmatchthepattern
$grepvcthisdemo_file
4
l.Displayonlythefilenameswhichmatchesthegivenpatternusinggrepl
Ifyouwantthegreptoshowoutonlythefilenameswhichmatchedthegivenpattern,usethe
l(lowercaseL)option.
Whenyougivemultiplefilestothegrepasinput,itdisplaysthenamesoffilewhichcontains
thetextthatmatchesthepattern,willbeveryhandywhenyoutrytofindsomenotesinyour
wholedirectorystructure.
$greplthisdemo_*
demo_file
demo_file1
m.Showonlythematchedstring
Bydefaultgrepwillshowthelinewhichmatchesthegivenpattern/string,butifyouwantthe
greptoshowoutonlythematchedstringofthepatternthenusetheooption.
Itmightnotbethatmuchusefulwhenyougivethestringstraightforward.Butitbecomes
veryusefulwhenyougivearegexpatternandtryingtoseewhatitmatchesas
$grepo"is.*line"demo_file
islineisthe1stlowercaseline
isline
isisthelastline
n.Showthepositionofmatchintheline
Whenyouwantgreptoshowthepositionwhereitmatchesthepatterninthefile,usethe
followingoptionsas
Syntax:
grepob"pattern"file
$cattempfile.txt
12345
12345
$grepob"3"tempfile.txt
2:3
8:3
Note:Theoutputofthegrepcommandaboveisnotthepositionintheline,itisbyteoffsetof
thewholefile.
o.Showlinenumberwhiledisplayingtheoutputusinggrepn
Toshowthelinenumberoffilewiththelinematched.Itdoes1basedlinenumberingforeach
file.Usenoptiontoutilizethisfeature.
$grepn"go"demo_text
5:*egototheendofthecurrentword.
6:*EgototheendofthecurrentWORD.
7:*bgototheprevious(before)word.
8:*Bgototheprevious(before)WORD.
9:*wgotothenextword.
10:*WgotothenextWORD.
2.FindFilesUsingNameandIgnoringCase
Thisisabasicusageofthefindcommand.Thisexamplefindsallfileswithname
MyCProgram.c(ignoringthecase)inthecurrentdirectoryandallitssubdirectories.
#findiname"MyCProgram.c"
./mycprogram.c
./backup/mycprogram.c
./backup/MyCProgram.c
./MyCProgram.c
3.LimitSearchToSpecificDirectoryLevelUsingmindepthandmaxdepth
Findthepasswdfileunderallsubdirectoriesstartingfromrootdirectory.
#find/namepasswd
./usr/share/doc/nss_ldap253/pam.d/passwd
./usr/bin/passwd
./etc/pam.d/passwd
./etc/passwd
Findthepasswdfileunderrootandoneleveldown.(i.erootlevel1,andonesubdirectory
level2)
#findmaxdepth2namepasswd
./etc/passwd
Findthepasswdfileunderrootandtwolevelsdown.(i.erootlevel1,andtwosub
directorieslevel2and3)
#find/maxdepth3namepasswd
./usr/bin/passwd
./etc/pam.d/passwd
./etc/passwd
Findthepasswordfilebetweensubdirectorylevel2and4.
#findmindepth3maxdepth5namepasswd
./usr/bin/passwd
./etc/pam.d/passwd
4.ExecutingCommandsontheFilesFoundbytheFindCommand.
Intheexamplebelow,thefindcommandcalculatesthemd5sumofallthefileswiththename
MyCProgram.c(ignoringcase).{}isreplacedbythecurrentfilename.
#findiname"MyCProgram.c"execmd5sum{}\;
d41d8cd98f00b204e9800998ecf8427e./mycprogram.c
d41d8cd98f00b204e9800998ecf8427e./backup/mycprogram.c
d41d8cd98f00b204e9800998ecf8427e./backup/MyCProgram.c
d41d8cd98f00b204e9800998ecf8427e./MyCProgram.c
5.Invertingthematch.
ShowsthefilesordirectorieswhosenamearenotMyCProgram.c.Sincethemaxdepthis1,
thiswilllookonlyundercurrentdirectory.
#findmaxdepth1notiname"MyCProgram.c"
.
./MybashProgram.sh
./create_sample_files.sh
./backup
./Program.c
6.FindingFilesbyitsinodeNumber.
Everyfilehasanuniqueinodenumber,usingthatwecanidentifythatfile.Createtwofiles
withsimilarname.i.eonefilewithaspaceattheend.
#touch"testfilename"
#touch"testfilename"
[Note:Thereisaspaceattheend]
#ls1test*
testfilename
testfilename
Fromthelsoutput,youcannotidentifywhichfilehasthespaceattheend.Usingoptioni,
youcanviewtheinodenumberofthefile,whichwillbedifferentforthesetwofiles.
#lsi1test*
16187429testfilename
16187430testfilename
Youcanspecifyinodenumberonafindcommandasshownbelow.Inthisexample,find
commandrenamesafileusingtheinodenumber.
#findinum16187430execmv{}newtestfilename\;
#lsi1*test*
16187430newtestfilename
16187429testfilename
Youcanusethistechniquewhenyouwanttodosomeoperationwiththefileswhichare
namedpoorlyasshownintheexamplebelow.Forexample,thefilewithnamefile?.txthas
aspecialcharacterinit.Ifyoutrytoexecutermfile?.txt,allthefollowingthreefileswillget
removed.So,followthestepsbelowtodeleteonlythefile?.txtfile.
#ls
file1.txtfile2.txtfile?.txt
Findtheinodenumbersofeachfile.
#lsi1
804178file1.txt
804179file2.txt
804180file?.txt
Usetheinodenumbertoremovethefilethathadspecialcharacterinitasshownbelow.
#findinum804180execrm{}\;
#ls
file1.txtfile2.txt
[Note:Thefilewithname"file?.txt"isnowremoved]
7.FindfilebasedontheFilePermissions
Followingoperationsarepossible.
Findfilesthatmatchexactpermission
Checkwhetherthegivenpermissionmatches,irrespectiveofotherpermissionbits
Searchbygivingoctal/symbolicrepresentation
Forthisexample,letusassumethatthedirectorycontainsthefollowingfiles.Pleasenotethat
thefilepermissionsonthesefilesaredifferent.
#lsl
total0
rwxrwxrwx1rootroot02009021920:31all_for_all
rwrr1rootroot02009021920:30everybody_read
1rootroot02009021920:31no_for_all
rw1rootroot02009021920:29ordinary_file
rwr1rootroot02009021920:27others_can_also_read
r1rootroot02009021920:27others_can_only_read
Findfileswhichhasreadpermissiontogroup.Usethefollowingcommandtofindallfilesthat
arereadablebytheworldinyourhomedirectory,irrespectiveofotherpermissionsforthatfile.
#find.permg=rtypefexeclsl{}\;
rwrr1rootroot02009021920:30./everybody_read
rwxrwxrwx1rootroot02009021920:31./all_for_all
r1rootroot02009021920:27./others_can_only_read
rwr1rootroot02009021920:27./others_can_also_read
Findfileswhichhasreadpermissiononlytogroup.
#find.permg=rtypefexeclsl{}\;
r1rootroot02009021920:27./others_can_only_read
Findfileswhichhasreadpermissiononlytogroup[searchbyoctal]
#find.perm040typefexeclsl{}\;
r1rootroot02009021920:27./others_can_only_read
8.Findallemptyfiles(zerobytefile)inyourhomedirectoryandits
subdirectory
Mostfilesofthefollowingcommandoutputwillbelockfilesandplaceholderscreatedby
otherapplications.
#find~empty
Listalltheemptyfilesonlyinyourhomedirectory.
#find.maxdepth1empty
Listonlythenonhiddenemptyfilesonlyinthecurrentdirectory.
#find.maxdepth1emptynotname".*"
9.FindingtheTop5BigFiles
Thefollowingcommandwilldisplaythetop5largestfileinthecurrentdirectoryandits
subdirectory.Thismaytakeawhiletoexecutedependingonthetotalnumberoffilesthe
commandhastoprocess.
#find.typefexeclss{}\;|sortnr|head5
10.FindingtheTop5SmallFiles
Techniqueissameasfindingthebiggerfiles,buttheonlydifferencethesortisascending
order.
#find.typefexeclss{}\;|sortn|head5
Intheabovecommand,mostprobablyyouwillgettoseeonlytheZERObytefiles(emptyfiles
).So,youcanusethefollowingcommandtolistthesmallerfilesotherthantheZERObyte
files.
#find.notemptytypefexeclss{}\;|sortn|head5
11.FindFilesBasedonfiletypeusingoptiontype
Findonlythesocketfiles.
#find.types
Findalldirectories
#find.typed
Findonlythenormalfiles
#find.typef
Findallthehiddenfiles
#find.typefname".*"
Findallthehiddendirectories
#findtypedname".*"
12.Findfilesbycomparingwiththemodificationtimeofotherfile.
Showfileswhicharemodifiedafterthespecifiedfile.Thefollowingfindcommanddisplaysall
thefilesthatarecreated/modifiedafterordinary_file.
#lslrt
total0
rwr1rootroot02009021920:27others_can_also_read
r1rootroot02009021920:27others_can_only_read
rw1rootroot02009021920:29ordinary_file
rwrr1rootroot02009021920:30everybody_read
rwxrwxrwx1rootroot02009021920:31all_for_all
1rootroot02009021920:31no_for_all
#findnewerordinary_file
.
./everybody_read
./all_for_all
./no_for_all
13.FindFilesbySize
Usingthesizeoptionyoucanfindfilesbysize.
Findfilesbiggerthanthegivensize
#find~size+100M
Findfilessmallerthanthegivensize
#find~size100M
Findfilesthatmatchestheexactgivensize
#find~size100M
Note:meanslessthanthegivesize,+meansmorethanthegivensize,andnosymbolmeans
exactgivensize.
14.CreateAliasforFrequentFindOperations
Ifyoufindsomethingasprettyuseful,thenyoucanmakeitasanalias.Andexecuteit
wheneveryouwant.
Removethefilesnameda.outfrequently.
#aliasrmao="find.inamea.outexecrm{}\;"
#rmao
Removethecorefilesgeneratedbycprogram.
#aliasrmc="find.inamecoreexecrm{}\;"
#rmc
15.Removebigarchivefilesusingfindcommand
Thefollowingcommandremoves*.zipfilesthatareover100M.
#find/typefname*.zipsize+100Mexecrmi{}\;"
Removeall*.tarfilethatareover100Musingthealiasrm100m(Remove100M).Usethe
similarconceptsandcreatealiaslikerm1g,rm2g,rm5gtoremovefilesizegreaterthan1G,2G
and5Grespectively.
#aliasrm100m="find/typefname*.tarsize+100Mexecrmi{}\;"
#aliasrm1g="find/typefname*.tarsize+1Gexecrmi{}\;"
#aliasrm2g="find/typefname*.tarsize+2Gexecrmi{}\;"
#aliasrm5g="find/typefname*.tarsize+5Gexecrmi{}\;"
#rm100m
#rm1g
#rm2g
#rm5g
FindFilesBasedonAccess/Modification/ChangeTime
You can find files based on following three file time attribute.
1. Accesstimeofthefile.Accesstimegetsupdatedwhenthefileaccessed.
2. Modificationtimeofthefile.Modificationtimegetsupdatedwhenthefilecontent
modified.
3. Changetimeofthefile.Changetimegetsupdatedwhentheinodedatachanges.
Inthefollowingexamples,thedifferencebetweentheminoptionandthetimeoptionisthe
argument.
minargumenttreatsitsargumentasminutes.Forexample,min60=60minutes(1hour).
timeargumenttreatsitsargumentas24hours.Forexample,time2=2*24hours(2days).
Whiledoingthe24hourscalculation,thefractionalpartsareignoredso25hoursistakenas
24hours,and47hoursisalsotakenas24hours,only48hoursistakenas48hours.Toget
moreclarityrefertheatimesectionofthefindcommandmanpage.
Example1:Findfileswhosecontentgotupdatedwithinlast1hour
Tofindthefilesbaseduponthecontentmodificationtime,theoptionmmin,andmtimeis
used.Followingisthedefinitionofmminandmtimefrommanpage.
mminnFilesdatawaslastmodifiednminutesago.
mtimenFilesdatawaslastmodifiedn*24hoursago.
Followingexamplewillfindfilesinthecurrentdirectoryandsubdirectories,whosecontent
gotupdatedwithinlast1hour(60minutes)
#find.mmin60
Inthesameway,followingexamplefindsallthefiles(underrootfilesystem/)thatgot
updatedwithinthelast24hours(1day).
#find/mtime1
Example2:Findfileswhichgotaccessedbefore1hour
Tofindthefilesbaseduponthefileaccesstime,theoptionamin,andatimeisused.
Followingisthedefinitionofaminandatimefromfindmanpage.
aminnFilewaslastaccessednminutesago
atimenFilewaslastaccessedn*24hoursago
Followingexamplewillfindfilesinthecurrentdirectoryandsubdirectories,whichgot
accessedwithinlast1hour(60minutes)
#findamin60
Inthesameway,followingexamplefindsallthefiles(underrootfilesystem/)thatgot
accessedwithinthelast24hours(1day).
#find/atime1
Example3:Findfileswhichgotchangedexactlybefore1hour
Tofindthefilesbaseduponthefileinodechangetime,theoptioncmin,andctimeisused.
Followingisthedefinitionofcminandctimefromfindmanpage.
cminnFilesstatuswaslastchangednminutesago.
ctimenFilesstatuswaslastchangedn*24hoursago.
Followingexamplewillfindfilesinthecurrentdirectoryandsubdirectories,whichchanged
withinlast1hour(60minutes)
#find.cmin60
Inthesameway,followingexamplefindsallthefiles(underrootfilesystem/)thatgot
changedwithinthelast24hours(1day).
#find/ctime1
Example4:Restrictingthefindoutputonlytofiles.
(Display only files as find command results)
Theabovefindcommandswillalsoshowthedirectoriesbecausedirectoriesgetsaccessed
whenthefileinsideitgetsaccessed.Butifyouwantonlythefilestobedisplayedthengive
typefinthefindcommandas
Thefollowingfindcommanddisplaysfilesthatareaccessedinthelast30minutes.
#find/etc/sysconfigamin30
.
./console
./networkscripts
./i18n
./rhn
./rhn/clientCaps.d
./networking
./networking/profiles
./networking/profiles/default
./networking/profiles/default/resolv.conf
./networking/profiles/default/hosts
./networking/devices
./apmscripts
[Note:Theaboveoutputcontainsbothfilesanddirectories]
#find/etc/sysconfigamin30typef
./i18n
./networking/profiles/default/resolv.conf
./networking/profiles/default/hosts
[Note:Theaboveoutputcontainsonlyfiles]
Example5:Restrictingthesearchonlytounhiddenfiles.
(Donotdisplayhiddenfilesinfindoutput)
Whenwedontwantthehiddenfilestobelistedinthefindoutput,wecanusethefollowing
regex.
Thebelowfinddisplaysthefileswhicharemodifiedinthelast15minutes.Anditlistsonlythe
unhiddenfiles.i.ehiddenfilesthatstartswitha.(period)arenotdisplayedinthefindoutput.
#find.mmin15\(!regex".*/\..*"\)
FindingFilesComparativelyUsingFindCommand
Humanmindcanrememberthingsbetterbyreferencesuchas,iwanttofindfileswhichi
editedaftereditingthefiletest.Youcanfindfilesbyreferringtotheotherfilesmodification
aslikethefollowing.
Example6:FindfileswhicharemodifiedaftermodificationofaparticularFILE
Syntax:findnewerFILE
Followingexampledisplaysallthefileswhicharemodifiedafterthe/etc/passwdfileswas
modified.Thisishelpful,ifyouwanttotrackalltheactivitiesyouvedoneafteraddinganew
user.
#findnewer/etc/passwd
Example7:FindfileswhichareaccessedaftermodificationofaspecificFILE
Syntax:findanewerFILE
Followingexampledisplaysallthefileswhichareaccessedaftermodifying/etc/hosts.Ifyou
rememberaddinganentrytothe/etc/hostsandwouldliketoseeallthefilesthatyouve
accessedsincethen,usethefollowingcommand.
#findanewer/etc/hosts
Example8:FindfileswhosestatusgotchangedafterthemodificationofaspecificFILE.
Syntax:findcnewerFILE
Followingexampledisplaysallthefileswhosestatusgotchangedaftermodifyingthe
/etc/fstab.Ifyourememberaddingamountpointinthe/etc/fstabandwouldliketoknowall
thefileswhostatusgotchangedsincethen,usethefollowingcommand.
findcnewer/etc/fstab
PerformAnyOperationonFilesFoundFromFindCommand
Wehavelookedatmanydifferentwaysoffindingfilesusingfindcommandinthisarticleand
alsoinourpreviousarticle.Ifyouarenotfamiliarinfindingfilesindifferentways,istrongly
recommendyoutoreadthepart1.
Thissectionexplainsabouthowtododifferentoperationonthefilesfromthefindcommand.
i.ehowtomanipulatethefilesreturnedbythefindcommandoutput.
Wecanspecifyanyoperationonthefilesfoundfromfindcommand.
find<CONDITIONtoFindfiles>exec<OPERATION>\;
TheOPERATIONcanbeanythingsuchas:
rmcommandtoremovethefilesfoundbyfindcommand.
mvcommandtorenamethefilesfound.
lslcommandtogetdetailsofthefindcommandoutputfiles.
md5sumonfindcommandoutputfiles
wccommandtocountthetotalnumberofwordsonfindcommandoutputfiles.
ExecuteanyUnixshellcommandonfindcommandoutputfiles.
orExecuteyourowncustomshellscript/commandonfindcommandoutputfiles.
Example9:lslinfindcommandoutput.
Long list the files which are edited within the last 1 hour.
#findmmin60
./cron
./secure
#findmmin60execlsl{}\;
rw1rootroot1028Jun2115:01./cron
rw1rootroot831752Jun2115:42./secure
Example10:SearchingOnlyintheCurrentFilesystem
Systemadministratorswouldwanttosearchintherootfilesystem,butnotintheother
mountedpartitions.Whenyouhavemultiplepartitionsmounted,andifyouwanttosearch
in/.Youcandothefollowing.
Followingcommandwillsearchfor*.logfilesstartingfrom/.i.eIfyouhavemultiple
partitionsmountedunder/(root),thefollowingcommandwillsearchallthosemounted
partitions.
#find/name"*.log"
Thiswillsearchforthefileonlyinthecurrentfilesystem.Followingisthexdevdefinition
fromfindmanpage:
xdevDontdescenddirectoriesonotherfilesystems.
Followingcommandwillsearchfor*.logfilesstartingfrom/(root)andonlyinthecurrentfile
system.i.eIfyouhavemultiplepartitionsmountedunder/(root),thefollowingcommand
willNOTsearchallthosemountedpartitions.
#find/xdevname"*.log"
Example11:Usingmorethanone{}insamecommand
Manualsaysonlyoneinstanceofthe{}ispossible.Butyoucanusemorethanone{}inthe
samecommandasshownbelow.
#findname"*.txt"cp{}{}.bkup\;
Usingthis{}inthesamecommandispossiblebutusingitindifferentcommanditisnot
possible,sayyouwanttorenamethefilesasfollowing,whichwillnotgivetheexpectedresult.
findname"*.txt"execmv{}`basename{}.htm`.html\;
Example12:Using{}inmorethanoneinstance.
Youcansimulateitbywritingashellscriptasshownbelow.
#mv"$1""`basename"$1".htm`.html"
Thesedoublequotesaretohandlespacesinfilename.Andthencallthatshellscriptfromthe
findcommandasshownbelow.
findname"*.html"exec./mv.sh'{}'\;
Soforanyreasonifyouwantthesamefilenametobeusedmorethanoncethenwritingthe
simpleshellscriptandpassingthefilenamesasargumentisthesimplestwaytodoit.
Example13:Redirectingerrorsto/dev/null
Redirectingtheerrorsisnotagoodpractice.Anexperienceduserunderstandstheimportance
ofgettingtheerrorprintedonterminalandfixit.
Particularlyinfindcommandredirectingtheerrorsisnotagoodpractice.Butifyoudont
wanttoseetheerrorsandwouldliketoredirectittonulldoitasshownbelow.
findname"*.txt"2>>/dev/null
Sometimesthismaybehelpful.Forexample,ifyouaretryingtofindallthe*.conffileunder/
(root)fromyouraccount,youmaygetlotofPermissiondeniederrormessageasshown
below.
$find/name"*.conf"
/sbin/generatemodprobe.conf
find:/tmp/orbitroot:Permissiondenied
find:/tmp/sshgccBMp5019:Permissiondenied
find:/tmp/keyring5iqiGo:Permissiondenied
find:/var/log/httpd:Permissiondenied
find:/var/log/ppp:Permissiondenied
/boot/grub/grub.conf
find:/var/log/audit:Permissiondenied
find:/var/log/squid:Permissiondenied
find:/var/log/samba:Permissiondenied
find:/var/cache/alchemist/printconf.rpm/wm:Permissiondenied
[Note:Therearetwovalid*.conffilesburnedinthe"Permissiondenied"messages]
So,ifyouwanttojustviewtherealoutputofthefindcommandandnotthePermission
deniederrormessageyoucanredirecttheerrormessageto/dev/nullasshownbelow.
$find/name"*.conf"2>>/dev/null
/sbin/generatemodprobe.conf
/boot/grub/grub.conf
[Note:Allthe"Permissiondenied"messagesarenotdisplayed]
Example14:Substitutespacewithunderscoreinthefilename.
Audiofilesyoudownloadfrominternetmostlycomewiththespacesinit.Buthavingspacein
thefilenameisnotsogoodforLinuxkindofsystems.Youcanusethefindandrename
commandcombinationasshownbelowtorenamethefiles,bysubstitutingthespacewith
underscore.
Thefollowingreplacesspaceinallthe*.mp3fileswith_
$find.typefiname*.mp3execrenames//_/g{}\;
Example15:Executingtwofindcommandsatthesametime
Asshownintheexamplesofthefindcommandinitsmanualpage,thefollowingisthesyntax
whichcanbeusedtoexecutetwocommandsinsingletraversal.
Thefollowingfindcommandexample,traversethefilesystemjustonce,listingsetuidfilesand
directoriesinto/root/suid.txtandlargefilesinto/root/big.txt.
#find/\(perm4000fprintf/root/suid.txt'%#m%u%p\n'\),\
\(size+100Mfprintf/root/big.txt'%10s%p\n'\)
ssh command
Logintoremotehost
sshljsmithremotehost.example.com
Debugsshclient
sshvljsmithremotehost.example.com
Displaysshclientversion
$sshV
OpenSSH_3.9p1,OpenSSL0.9.7aFeb192003
sed command
Sedregularexpressions
Thesedregularexpressionsareessentiallythesameasthegrepregularexpressions.Theyare
summarizedbelow.
^
matchesthebeginningoftheline
$
matchestheendoftheline
.
Matchesanysinglecharacter
(character)*
matcharbitrarilymanyoccurencesof(character)
(character)?
Match0or1instanceof(character)
[abcdef]
[^abcdef]
(character)\{m,n\}
(character)\{m,\}
(character)\{,n\}
(character)\{n\}
\(expression\)
\n
expression1\|
expression2
Matchanycharacterenclosedin[](inthisinstance,abcdeorf)
rangesofcharacterssuchas[az]arepermitted.Thebehaviourofthis
deservesmoredescription.Seethepageongrepformoredetailsabout
thesyntaxoflists.
MatchanycharacterNOTenclosedin[](inthisinstance,anycharacter
otherthanabcdeorf)
Matchmnrepetitionsof(character)
Matchmormorerepetitionsof(character)
Matchnorless(possibly0)repetitionsof(character)
Matchexactlynrepetitionsof(character)
Groupoperator.
Backreferencematchesnthgroup
Matchesexpression1orexpression2.WorkswithGNUsed,butthis
featuremightnotworkwithotherformsofsed.
SpecialCharacters
Thespecialcharacterinsedarethesameasthoseingrep,withonekeydifference:theforward
slash/isaspecialcharacterinsed.Thereasonforthiswillbecomeveryclearwhenstudying
sedcommands.
HowitWorks:ABriefIntroduction
Sedworksasfollows:itreadsfromthestandardinput,onelineatatime.foreachline,it
executesaseriesofeditingcommands,thenthelineiswrittentoSTDOUT.Anexamplewhich
showshowitworks:weusethessommand.smeans"substitute"orsearchandreplace.The
formatis
s/regularexpression/replacementtext/{flags}
Wewon'tdiscussalltheflagsyet.Theoneweusebelowisgwhichmeans"replaceall
matches"
>catfile
Ihavethreedogsandtwocats
>sede's/dog/cat/g'e's/cat/elephant/g'file
Ihavethreeelephantsandtwoelephants
>
OK.Sowhathappened?Firstly,sedreadinthelineofthefileandexecuted
s/dog/cat/g
whichproducedthefollowingtext:
Ihavethreecatsandtwocats
andthenthesecondcommandwasperformedontheeditedlineandtheresultwas
Ihavethreeelephantsandtwoelephants
Weactuallyhaveanameforthe"currenttext":itiscalledthepatternspace.Soaprecise
definitionofwhatseddoesisasfollows:
sedreadsthestandardinputintothepatternspace,performsasequenceofediting
commandsonthepatternspace,thenwritesthepatternspacetoSTDOUT.
GettingStarted:SubstituteanddeleteCommands
Firstly,thewayyouusuallyusesedisasfollows:
>sede'command1'e'command2'e'command3'file
>{shellcommand}|sede'command1'e'command2'
>sedfsedscript.sedfile
>{shellcommand}|sedfsedscript.sed
sosedcanreadfromafileorSTDIN,andthecommandscanbespecifiedinafileoronthe
commandline.Notethefollowing:
thatifthecommandsarereadfromafile,trailingwhitespacecanbefatal,in
particular,itwillcausescriptstofailfornoapparentreason.Irecommendediting
sedscriptswithaneditorsuchasvimwhichcanshowendoflinecharacterssothat
youcan"see"trailingwhitespaceattheendofline.
TheSubstituteCommand
Theformatforthesubstitutecommandisasfollows:
[address1[,address2]]s/pattern/replacement/[flags]
Theflagscanbeanyofthefollowing:
n
replacenthinstanceofpatternwithreplacement
g
replaceallinstancesofpatternwithreplacement
writepatternspacetoSTDOUTifasuccessfulsubstitutiontakes
p
place
w
Writethepatternspacetofileifasuccessfulsubstitutiontakes
file place
Ifnoflagsarespecifiedthefirstmatchonthelineisreplaced.notethatwewillalmostalways
usethescommandwitheitherthegflagornoflagatall.
Ifoneaddressisgiven,thenthesubstitutionisappliedtolinescontainingthataddress.An
addresscanbeeitheraregularexpressionenclosedbyforwardslashes/regex/,oraline
number.The$symbolcanbeusedinplaceofalinenumbertodenotethelastline.
Iftwoaddressesaregivenseparatedbyacomma,thenthesubstitutionisappliedtoalllines
betweenthetwolinesthatmatchthepattern.
Thisrequiressomeclarificationinthecasewherebothaddressesarepatterns,asthereissome
ambiguityhere.moreprecisely,thesubstitutionisappliedtoalllinesfromthefirstmatchof
address1tothefirstmatchofaddress2andalllinesfromthefirstmatchofaddress1following
thefirstmatchofaddress2tothenextmatchofaddress1Don'tworryifthisseemsvery
confusing(itis),theexampleswillclarifythis.
TheDeleteCommand
Thedeletecommandisverysimpleinitssyntax:itgoeslikethis
[address1,address2]]d
Anditdeletesthecontentofthepatternspace.Allfollowingcommandsareskipped(afterall,
there'sverylittleyoucandowithanemptypatternspace),andanewlineisreadintothe
patternspace.
Example1
>catfile
http://www.foo.com/mypage.html
>sede's@http://www.foo.com@http://www.bar.net@'file
http://www.bar.net/mypage.html
Notethatweusedadifferentdelimiter,@forthesubstitutioncommand.Sedpermitsseveral
delimitersforthescommandincluding@%,;:thesealternativedelimitersaregoodfor
substitutionswhichincludestringssuchasfilenames,asitmakesyoursedcodemuchmore
readable.
Example2
>catfile
theblackcatwaschasedbythebrowndog
>sede's/black/white/g'file
thewhitecatwaschasedbythebrowndog
Thatwasprettystraightforward.Nowwemoveontosomethingmoreinteresting.
Example3
>catfile
theblackcatwaschasedbythebrowndog.
theblackcatwasnotchasedbythebrowndog
>sede'/not/s/black/white/g'file
theblackcatwaschasedbythebrowndog.
thewhitecatwasnotchasedbythebrowndog.
Inthisinstance,thesubstitutionisonlyappliedtolinesmatchingtheregularexpressionnot.
Henceitisnotappliedtothefirstline.
Example4
>catfile
line1(one)
line2(two)
line3(three)
Example4a
>sede'1,2d'file
line3(three)
Example4b
>sede'3d'file
line1(one)
line2(two)
Example4c
>sede'1,2s/line/LINE/'file
LINE1(one)
LINE2(two)
line3(three)
Example4d
>sede'/^line.*one/s/line/LINE/'e'/line/d'file
LINE1(one)
3a:Thiswasprettysimple:wejustdeletedlines1to2.
3b:Thiswasalsoprettysimple.Wedeletedline3.
3c:Inthisexample,weperformedasubstitutiononlines12.
3d:nowthisismoreinteresting,anddeservessomeexplanation.Firstly,itisclearthatline2
and3getdeleted.Butlet'slookcloselyatwhathappenstoline1.
First,line1isreadintothepatternspace.Itmatchestheregularexpression^line.*oneSothe
substitutioniscarriedout,andtheresultingpatternspacelookslikethis:
LINE1(one)
Sonowthesecondcommandisexecuted,butsincethepatternspacedoesnotmatchthe
regularexpressionline,thedeletecommandisnotexecuted.
Example5
>catfile
hello
thistextiswipedout
Wipedout
hello(alsowipedout)
WiPedoutTOO!
goodbye
(1)Thistextisnotdeleted
(2)neitheristhis...(goodbye)
(3)neitheristhis
hello
butthisis
andsoisthis
andunlesswefindanotherg**dbye
everylinetotheendofthefilegetsdeleted
>sede'/hello/,/goodbye/d'file
(1)Thistextisnotdeleted
(2)neitheristhis...(goodbye)
(3)neitheristhis
Thisillustrateshowtheaddressingworkswhentwopatternaddressesarespecified.sedfinds
thefirstmatchoftheexpression"hello",deletingeverylinereadintothepatternspaceuntilit
getstothefirstlineaftertheexpression"goodbye".Itdoesn'tapplythedeletecommandtoany
moreaddressesuntilitcomesacrosstheexpression"hello"again.Sincetheexpression
"goodbye"isnotonanysubsequentline,thedeletecommandisappliedtoallremaininglines.
awk command
Removeduplicatelinesusingawk
$awk'!($0inarray){array[$0];print}'temp
Printalllinesfrom/etc/passwdthathasthesameuidandgid
$awkF':''$3==$4'passwd.txt
Printonlyspecificfieldfromafile.
$awk'{print$2,$5;}'employee.txt
diff command
Tocomparethecontentsoftwofiles:
diffemailaddresses
2a3,4
>[email protected]
>Jimjim@frolix8
Thisdisplaysalinebylinedifferencebetweenthefileemailandaddresses.
Tomakethesefilesmatchyouneedtoadd(a)lines3and4(3,4)ofthefileaddresses(>)
afterline2inthefileemail.
Herearethecontentsoffilesemailandaddressesusedinthisexample.Linenumbersare
shownatthebeginningofeachlinetohelpyoufollowthisexample.
emailaddresses
1Johnerpl08@ed1Johnerpl08@ed
[email protected]@cern.ch
[email protected]@pollux.ucs.co
4Keithkeith@festival4Jimjim@frolix8
[email protected]
6Keithkeith@festival
sort command
Tosortthefile
TosortthefruitsfilewiththeLC_ALL,LC_COLLATE,orLANGenvironmentvariablesetto
En_US,enter:
LANG=En_USsortfruits
Thiscommandsequencedisplaysthecontentsofthefruitsfilesortedinascending
lexicographicorder.Thecharactersineachcolumnarecomparedonebyone,including
spaces,digits,andspecialcharacters.Forinstance,ifthefruitsfilecontainsthetext:
banana
orange
Persimmon
apple
%%banana
apple
ORANGE
thesortcommanddisplays:
%%banana
ORANGE
Persimmon
apple
apple
banana
orange
IntheASCIIcollatingsequence,the%(percentsign)precedesuppercaseletters,which
precedelowercaseletters.Ifyourcurrentlocalespecifiesacharactersetotherthan
ASCII,yourresultsmaybedifferent.
Tosortindictionaryorder
sortdfruits
Thiscommandsequencesortsanddisplaysthecontentsofthefruitsfile,comparing
onlyletters,digits,andspaces.Ifthefruitsfileisthesameasinexample1,thenthe
sortcommanddisplays:
ORANGE
Persimmon
apple
apple
%%banana
banana
orange
Thedflagignoresthe%(percentsign)characterbecauseitisnotaletter,digit,or
space,placing%%bananawithbanana.
Togrouplinesthatcontainuppercaseandspecialcharacterswithsimilarlowercaselines
sortd
f
fruits
Thedflagignoresspecialcharactersandthefflagignoresdifferencesincase.With
theLC_ALL,LC_COLLATE,orLANGenvironmentvariablesettoC,theoutputforthe
fruitsfilebecomes:
apple
apple
%%banana
banana
ORANGE
orange
Persimmon
Tosort,removingduplicatelines
sortdfufruits
Theuflagtellsthesortcommandtoremoveduplicatelines,makingeachlineofthe
fileunique.Thiscommandsequencedisplays:
apple
%%banana
ORANGE
Persimmon
Notonlyistheduplicateappleremoved,butbananaandORANGEaswell.Theseare
removedbecausethedflagignoresthe%%specialcharactersandthefflagignores
differencesincase.
1. Tosortasinexample4,removingduplicateinstancesunlesscapitalizedorpunctuated
differently,enter:
sortu+0d
f
+0fruits
Enteringthe+0dfdoesthesametypeofsortthatisdonewithdfinexample3.
Thenthe+0performsanothercomparisontodistinguishlinesthatarenotidentical.
Thispreventstheuflagfromremovingthem.
Giventhefruitsfileshowninexample1,theadded+0distinguishes%%bananafrom
bananaandORANGEfromorange.However,thetwoinstancesofappleareidentical,so
oneofthemisdeleted.
apple
%%banana
banana
ORANGE
orange
Persimmon
Tospecifythecharacterthatseparatesfields
sortt:+1vegetables
Thiscommandsequencesortsthevegetablesfile,comparingthetextthatfollowsthe
firstcolononeachline.The+1tellsthesortcommandtoignorethefirstfieldandto
comparefromthestartofthesecondfieldtotheendoftheline.Thet:flagtellsthe
sortcommandthatcolonsseparatefields.Ifvegetablescontains:
yams:104
turnips:8
potatoes:15
carrots:104
greenbeans:32
radishes:5
lettuce:15
Then,withtheLC_ALL,LC_COLLATE,orLANGenvironmentvariablesettoC,thesort
commanddisplays:
carrots:104
yams:104
lettuce:15
potatoes:15
greenbeans:32
radishes:5
turnips:8
Notethatthenumbersarenotinnumericorder.Thishappenedwhenalexicographic
sortcompareseachcharacterfromlefttoright.Inotherwords,3comesbefore5,so32
comesbefore5.
Tosortnumbers
sortt:+1nvegetables
Thiscommandsequencesortsthevegetablesfilenumericallyonthesecondfield.Ifthe
vegetablesfileisthesameasinexample6,thenthesortcommanddisplays:
radishes:5
turnips:8
lettuce:15
potatoes:15
greenbeans:32
carrots:104
yams:104
Tosortmorethanonefield
sortt:+12n+01rvegetables
OR
sortt:k2,2n
k
1,1rvegetables
Thiscommandsequenceperformsanumericsortonthesecondfield(+12n).Within
thatordering,itsortsthefirstfieldinreversealphabeticorder(+01r).Withthe
LC_ALL,LC_COLLATE,orLANGenvironmentvariablesettoC,theoutputlookslike
this:
radishes:5
turnips:8
potatoes:15
lettuce:15
greenbeans:32
yams:104
carrots:104
Thecommandsortsthelinesinnumericorder.Whentwolineshavethesamenumber,
theyappearinreversealphabeticorder.
Toreplacetheoriginalfilewiththesortedtext
sortovegetablesvegetables
Thiscommandsequencestoresthesortedoutputintothevegetablesfile(o
vegetables).
Sortafileindescendingorder
$sortrnames.txt
export command
Tovieworaclerelatedenvironmentvariables.
$export|grepORACLE
declarexORACLE_BASE="/u01/app/oracle"
declarexORACLE_HOME="/u01/app/oracle/product/10.2.0"
declarexORACLE_SID="med"
declarexORACLE_TERM="xterm"
Toexportanenvironmentvariable:
$exportORACLE_HOME=/u01/app/oracle/product/10.2.0
gzipcommand
Tocreatea*.gzcompressedfile:
$gziptest.txt
Touncompressa*.gzfile:
$gzipdtest.txt.gz
Displaycompressionratioofthecompressedfileusinggzipl
$gzipl*.gz
compresseduncompressedratiouncompressed_name
237099797575.8%asppatchrpms.txt
bzip2 command
Tocreatea*.bz2compressedfile:
$bzip2test.txt
Touncompressa*.bz2file:
bzip2dtest.txt.bz2
unzip command
Toextracta*.zipcompressedfile:
$unziptest.zip
Viewthecontentsof*.zipfile(Withoutunzippingit):
$unzipljasper.zip
Archive:jasper.zip
LengthDateTimeName
4099511309823:50METAINF/MANIFEST.MF
3216908259821:07classes_
1596408259821:07classes_names
1054208259821:07classes_ncomp
ps command
pscommandisusedtodisplayinformationabouttheprocessesthatarerunninginthesystem.
Whiletherearelotofargumentsthatcouldbepassedtoapscommand,followingaresomeof
thecommonones.
Toviewcurrentrunningprocesses.
$psef|more
Toviewcurrentrunningprocessesinatreestructure.Hoptionstandsforprocesshierarchy.
$psefH|more
top command
topcommanddisplaysthetopprocessesinthesystem(bydefaultsortedbycpuusage).To
sorttopoutputbyanycolumn,PressO(uppercaseO),whichwilldisplayallthepossible
columnsthatyoucansortbyasshownbelow.
CurrentSortField:Pforwindow1:Def
Selectsortfieldviafieldletter,typeanyotherkeytoreturn
a:PID=ProcessIdv:nDRT=DirtyPagescount
d:UID=UserIdy:WCHAN=SleepinginFunction
e:USER=UserNamez:Flags=TaskFlags
Todisplaysonlytheprocessesthatbelongtoaparticularuseruseuoption.Thefollowingwill
showonlythetopprocessesthatbelongstooracleuser.
$topuoracle
dfcommand
Displaysthefilesystemdiskspaceusage.Bydefaultdfkdisplaysoutputinbytes.
$dfk
Filesystem1KblocksUsedAvailableUse%Mountedon
/dev/sda12953040032331042479723212%/
/dev/sda2120367992501715966408206044%/home
dfhdisplaysoutputinhumanreadableform.i.esizewillbedisplayedinGBs.
ramesh@rameshlaptop:~$dfh
FilesystemSizeUsedAvailUse%Mountedon
/dev/sda129G3.1G24G12%/
/dev/sda2115G48G62G44%/home
UseToptiontodisplaywhattypeoffilesystem.
ramesh@rameshlaptop:~$dfT
FilesystemType1KblocksUsedAvailableUse%Mountedon
/dev/sda1ext42953040032331202479721612%/
/dev/sda2ext4120367992501715966408206044%/home
mountcommand
Tomountafilesystem,youshouldfirstcreateadirectoryandmountitasshownbelow.
#mkdir/u01
#mount/dev/sdb1/u01
Youcanalsoaddthistothefstabforautomaticmounting.i.eAnytimesystemisrestarted,the
filesystemwillbemounted.
/dev/sdb1/u01ext2defaults02
chmod command
chmodcommandisusedtochangethepermissionsforafileordirectory.
Givefullaccesstouserandgroup(i.eread,writeandexecute)onaspecificfile.
$chmodug+rwxfile.txt
Revokeallaccessforthegroup(i.eread,writeandexecute)onaspecificfile.
$chmodgrwxfile.txt
Applythefilepermissionsrecursivelytoallthefilesinthesubdirectories.
$chmodRug+rwxfile.txt
Followingarethesymbolicrepresentationofthreedifferentroles:
uisforuser,
gisforgroup,
andoisforothers.
Followingarethesymbolicrepresentationofthreedifferentpermissions:
risforreadpermission,
wisforwritepermission,
xisforexecutepermission.
Followingarefewexamplesonhowtousethesymbolicrepresentationonchmod.
1.Addsinglepermissiontoafile/directory
Changingpermissiontoasingleset.+symbolmeansaddingpermission.Forexample,dothe
followingtogiveexecutepermissionfortheuserirrespectiveofanythingelse:
$chmodu+xfilename
2.Addmultiplepermissiontoafile/directory
Usecommatoseparatethemultiplepermissionsetsasshownbelow.
$chmodu+r,g+xfilename
3.Removepermissionfromafile/directory
Followingexampleremovesreadandwritepermissionfortheuser.
$chmodurxfilename
4.Changepermissionforallrolesonafile/directory
Followingexampleassignsexecuteprivilegetouser,groupandothers(basicallyanybodycan
executethisfile).
$chmoda+xfilename
5.Makepermissionforafilesameasanotherfile(usingreference)
Ifyouwanttochangeafilepermissionsameasanotherfile,usethereferenceoptionasshown
below.Inthisexample,file2spermissionwillbesetexactlysameasfile1spermission.
$chmodreference=file1file2
6.Applythepermissiontoallthefilesunderadirectoryrecursively
UseoptionRtochangethepermissionrecursivelyasshownbelow.
$chmodR755directoryname/
7.Changeexecutepermissiononlyonthedirectories(filesarenotaffected)
Onaparticulardirectoryifyouhavemultiplesubdirectoriesandfiles,thefollowingcommand
willassignexecutepermissiononlytoallthesubdirectoriesinthecurrentdirectory(notthe
filesinthecurrentdirectory).
$chmodu+X*
chowncommand
chowncommandisusedtochangetheownerandgroupofafile.\
Tochangeownertooracleandgrouptodbonafile.i.eChangebothownerandgroupatthe
sametime.
$chownoracle:dbadbora.sh
UseRtochangetheownershiprecursively.
$chownRoracle:dba/home/oracle
passwd command
Changeyourpasswordfromcommandlineusingpasswd.Thiswillpromptfortheold
passwordfollowedbythenewpassword.
$passwd
Superusercanusepasswdcommandtoresetotherspassword.Thiswillnotpromptfor
currentpasswordoftheuser.
#passwdUSERNAME
Removepasswordforaspecificuser.Rootusercandisablepasswordforaspecificuser.Once
thepasswordisdisabled,theusercanloginwithoutenteringthepassword.
#passwddUSERNAME
su command examples
Switchtoadifferentuseraccountusingsucommand.Superusercanswitchtoanyotheruser
withoutenteringtheirpassword.
$suUSERNAME
Executeasinglecommandfromadifferentaccountname.Inthefollowingexample,johncan
executethelscommandasrajusername.Oncethecommandisexecuted,itwillcomebackto
johnsaccount.
[john@devserver]$surajc'ls'
[john@devserver]$
Logintoaspecifieduseraccount,andexecutethespecifiedshellinsteadofthedefaultshell.
$sus'SHELLNAME'USERNAME
Onceyouvechangedthesystemdate,youshouldsyncronizethehardwareclockwiththe
systemdateasshownbelow.
#hwclocksystohc
hwclocksystohcutc