Anda di halaman 1dari 43

3/5/2016 LinuxandUnixfindcommandhelpandexamples

LinuxandUnixfindcommand
Quicklinks
Aboutfind
Syntax
Examples
Relatedcommands
LinuxandUnixmainpage

Aboutfind
findsearchesforfilesinadirectoryhierarchy.

Syntax

find[H][L][P][Ddebugopts][Olevel][path...][expression]

Description
findlocatesfilesonyoursystem.Withineachdirectorytreespecifiedbythegivenpaths,it
evaluatesthegivenexpressionfromlefttoright,accordingtotherulesofprecedence(see
"Operators",below)untiltheoutcomeisknown.Theoutcomeis"known"whentheleft
handsideoftheexpressionisdeterminedtobeFALSEforANDoperations,orTRUEfor
ORoperations.Atthatpointfindmovesontothenextpathuntilallpathshavebeen
searched.

findisafundamentalandextremelypowerfultoolforworkingwiththefilesonyourlinux
system.Itcanbeusedonitsowntolocatefiles,orinconjunctionwithotherprogramsto
performoperationsonthosefiles.

Options
http://www.computerhope.com/unix/ufind.htm 1/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

TheH,LandPoptionscontrolthetreatmentofsymboliclinks.Argumentsfollowing
thesearetakentobenamesoffilesordirectoriestobeexamined,uptothefirstargument
thatbeginswith"",ortheargument"("or"!".Thatargumentandanyfollowingarguments
aretakentobetheexpressiondescribingwhatistobesearchedfor.Ifnopathsaregiven,
thecurrentdirectoryisused.Ifnoexpressionisgiven,theexpressionprintisused(but
youshouldprobablyconsiderusingprint0instead,anyway.Moreinformationonthis
below).

Theargumentsintheexpressionlistarealsoreferredtoas"options,"butthefive"real"
optionsH,L,P,DandOmustappearbeforethefirstpathname,iftheyareusedatall.
Adoubledash("")canalsobeusedtosignalthatanyremainingargumentsarenot
options(thoughensuringthatallstartpointsbeginwitheither"./"or"/"isgenerallysaferif
youusewildcardsinthelistofstartpoints).

Neverfollowsymboliclinks.Thisisthedefault.Whenfindexaminesorprints
P informationafile,andthefileisasymboliclink,theinformationusedwillbetaken
fromthepropertiesofthesymboliclinkitself.

Followsymboliclinks.Whenfindexaminesorprintsinformationaboutfiles,the
L informationusedwillbetakenfromthepropertiesofthefiletowhichthelinkpoints,
notfromthelinkitself(unlessitisabrokensymboliclinkorfindisunableto
examinethefiletowhichthelinkpoints).Useofthisoptionimpliesnoleaf.Ifyou
laterusethePoption,noleafwillstillbeineffect.IfLisineffectandfind
discoversasymboliclinktoasubdirectoryduringitssearch,thesubdirectorypointed
tobythesymboliclinkwillbesearched.

WhentheLoptionisineffect,thetypepredicatewillalwaysmatchagainstthe
typeofthefilethatasymboliclinkpointstoratherthanthelinkitself(unlessthe
symboliclinkisbroken).UsingLcausesthelnameandilnamepredicatesalways
toreturnfalse.

Donotfollowsymboliclinks,exceptwhileprocessingthecommandlinearguments.
H Whenfindexaminesorprintsinformationaboutfiles,theinformationusedwillbe
http://www.computerhope.com/unix/ufind.htm 2/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

takenfromthepropertiesofthesymboliclinkitself.Theonlyexceptiontothis
behaviouriswhenafilespecifiedonthecommandlineisasymboliclink,andthe
linkcanberesolved.Forthatsituation,theinformationusedistakenfromwhatever
thelinkpointsto(thatis,thelinkisfollowed).Theinformationaboutthelinkitselfis
usedasafallbackifthefilepointedtobythesymboliclinkcannotbeexamined.If
Hisineffectandoneofthepathsspecifiedonthecommandlineisasymboliclink
toadirectory,thecontentsofthatdirectorywillbeexamined(thoughspecifying
maxdepth0wouldpreventthis).

IfmorethanoneofH,LandPisspecified,eachoverridestheothersthelastone
appearingonthecommandlinetakeseffect.Sinceitisthedefault,thePoptionshouldbe
consideredtobeineffectunlesseitherHorLisspecified.GNUfindfrequentlystats
filesduringtheprocessingofthecommandlineitself,beforeanysearchinghasbegun.
Theseoptionsalsoaffecthowthoseargumentsareprocessed.Specifically,therearea
numberofteststhatcomparefileslistedonthecommandlineagainstafilewearecurrently
considering.Ineachcase,thefilespecifiedonthecommandlinewillhavebeenexamined
andsomeofitspropertieswillhavebeensaved.Ifthenamedfileisinfactasymboliclink,
andthePoptionisineffect(orifneitherHnorLwerespecified),theinformationused
forthecomparisonwillbetakenfromthepropertiesofthesymboliclink.Otherwise,itwill
betakenfromthepropertiesofthefilethelinkpointsto.Iffindcannotfollowthelink(for
examplebecauseithasinsufficientprivilegesorthelinkpointstoanonexistentfile)the
propertiesofthelinkitselfwillbeused.

WhentheHorLoptionsareineffect,anysymboliclinkslistedastheargumentof
newerwillbedereferenced,andthetimestampwillbetakenfromthefiletowhichthe
symboliclinkpoints.ThesameconsiderationappliestonewerXY,anewerandcnewer.

ThefollowoptionhasasimilareffecttoL,thoughittakeseffectatthepointwhereit
appears(thatis,ifLisnotusedbutfollowis,anysymboliclinksappearingafterfollow
onthecommandlinewillbedereferenced,andthosebeforeitwillnot).

Ddebugoptions Printdiagnosticinformationthiscanbehelpfultodiagnose

http://www.computerhope.com/unix/ufind.htm 3/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

problemswithwhyfindisnotdoingwhatyouwant.Thelist
ofdebugoptionsshouldbecommaseparated.Compatibility
ofthedebugoptionsisnotguaranteedbetweenreleasesof
findutils.Foracompletelistofvaliddebugoptions,seethe
outputoffindDhelp.Validdebugoptionsinclude:

help Explainthedebuggingoptions.

tree Showtheexpressiontreeinitsoriginaland
optimisedform.

stat Printmessagesasfilesareexaminedwiththe
statandlstatsystemcalls.Thefindprogram
triestominimisesuchcalls.

opt Printsdiagnosticinformationrelatingtothe
optimisationoftheexpressiontreeseetheO
option.

rates Printsasummaryindicatinghowofteneach
predicatesucceededorfailed.

Olevel Enablesqueryoptimisation.Thefindprogramreorderstests
tospeedupexecutionwhilepreservingtheoveralleffect
thatis,predicateswithsideeffectsarenotreorderedrelative
toeachother.Theoptimisationsperformedateach
optimisationlevelareasfollows.

TheremustnotbeaspaceinbetweenOandthedecimal
representingtheoptimizationlevel.Thedecimalsandtheir
meaningsareasfollows:

http://www.computerhope.com/unix/ufind.htm 4/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

0 Equivalenttooptimisationlevel1.

1 Thisisthedefaultoptimisationleveland
correspondstothetraditionalbehaviour.
Expressionsarereorderedsothattestsbasedonly
onthenamesoffiles(forexamplenameand
regex)areperformedfirst.

2 Anytypeorxtypetestsareperformedafterany
testsbasedonlyonthenamesoffiles,butbefore
anyteststhatrequireinformationfromtheinode.
OnmanymodernversionsofUnix,filetypesare
returnedbyreaddir()andsothesepredicatesare
fastertoevaluatethanpredicateswhichneedto
statthefilefirst.

3 Atthisoptimisationlevel,thefullcostbased
queryoptimiserisenabled.Theorderoftestsis
modifiedsothatcheap(i.e.fast)testsare
performedfirstandmoreexpensiveonesare
performedlater,ifnecessary.Withineachcost
band,predicatesareevaluatedearlierorlater
accordingtowhethertheyarelikelytosucceedor
not.Foro,predicateswhicharelikelytosucceed
areevaluatedearlier,andfora,predicateswhich
arelikelytofailareevaluatedearlier.

Thecostbasedoptimiserhasafixedideaofhowlikelyany
giventestistosucceed.Insomecasestheprobabilitytakes
accountofthespecificnatureofthetest(forexample,type
fisassumedtobemorelikelytosucceedthantypec).The
costbasedoptimiseriscurrentlybeingevaluated.Ifitdoes
notactuallyimprovetheperformanceoffind,itwillbe

http://www.computerhope.com/unix/ufind.htm 5/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

removedagain.Conversely,optimisationsthatprovetobe
reliable,robustandeffectivemaybeenabledatlower
optimisationlevelsovertime.However,thedefault
behaviour(i.e.optimisationlevel1)willnotbechangedin
the4.3.xreleaseseries.Thefindutilstestsuiterunsallthe
testsonfindateachoptimisationlevelandensuresthatthe
resultisthesame.

Expressions
Theexpressionismadeupofoptions(whichaffectoveralloperationratherthanthe
processingofaspecificfile,andalwaysreturntrue),tests(whichreturnatrueorfalse
value),andactions(whichhavesideeffectsandreturnatrueorfalsevalue),allseparated
byoperators.andisassumedwheretheoperatorisomitted.

Iftheexpressioncontainsnoactionsotherthanprune,printisperformedonallfilesfor
whichtheexpressionistrue.

ExpressionOptions
Alloptionsalwaysreturntrue.Exceptfordaystart,followandregextype,theoptions
affectalltests,includingtestsspecifiedbeforetheoption.Thisisbecausetheoptionsare
processedwhenthecommandlineisparsed,whilethetestsdon'tdoanythinguntilfilesare
examined.Thedaystart,followandregextypeoptionsaredifferentinthisrespect,and
haveaneffectonlyontestswhichappearlaterinthecommandline.Therefore,forclarity,
itisbesttoplacethematthebeginningoftheexpression.Awarningisissuedifyoudon't
dothis.

d Asynonymfordepth,forcompatibilitywithFreeBSD,
NetBSD,MacOSXandOpenBSD.

daystart Measuretimes(foramin,atime,cmin,ctime,mmin,and
mtime)fromthebeginningoftodayratherthanfrom24
http://www.computerhope.com/unix/ufind.htm 6/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

hoursago.Thisoptiononlyaffectstestswhichappearlateron
thecommandline.

depth Processeachdirectory'scontentsbeforethedirectoryitself.
Thedeleteactionalsoimpliesdepth.

follow ThisisanolderwaytodothesamethingasL.Itisnow
deprecatedyoushouldusetheLoptioninstead.

Thisoptiondereferencessymboliclinksandimpliesnoleaf.
Thefollowoptionaffectsonlythosetestswhichappearafter
itonthecommandline.UnlesstheHorLoptionhasbeen
specified,thepositionofthefollowoptionchangesthe
behaviourofthenewerpredicateanyfileslistedasthe
argumentofnewerwillbedereferencediftheyaresymbolic
links.ThesameconsiderationappliestonewerXY,anewer
andcnewer.Similarly,thetypepredicatewillalwaysmatch
againstthetypeofthefilethatasymboliclinkpointstorather
thanthelinkitself.Usingfollowcausesthelnameand
ilnamepredicatesalwaystoreturnfalse.

help,help Printahelpmessage,andexit.

ignore_readdir_race Normally,findwillgiveanerrormessagewhenitcannotstat
afile.Ifyougivethisoptionandafileisdeletedbetweenthe
timefindreadsthenameofthefilefromthedirectoryandthe
timeittriestostatthefile,noerrormessagewillbeissued.
Thisalsoappliestopathsgivenonthecommandline.This
optiontakeseffectatthetimethecommandlineisread,which
meansthatyoucannotsearchonepartofthefilesystemwith
thisoptiononandpartofitwiththisoptionoff.

maxdepthlevels Descendatmostlevels(anonnegativeinteger)levelsof
directoriesbelowthecommandlinearguments.maxdepth0
http://www.computerhope.com/unix/ufind.htm 7/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

meansonlyapplythetestsandactionstothepathsspecified
onthecommandline,anddonotdescendintosubdirectoriesat
all.

mindepthlevels Donotapplyanytestsoractionsatlevelslessthanlevels(a
nonnegativeinteger).mindepth1meansprocessallfiles
exceptthecommandlinearguments.

mount Don'tdescenddirectoriesonotherfilesystems.Analternate
nameforxdev.Thisoptionisprovidedforcompatibilitywith
someotherversionsoffind.

Turnsofftheeffectofignore_readdir_race.
noignore_readdir_race

noleaf Donotoptimizebyassumingthatdirectoriescontain2fewer
subdirectoriesthantheirhardlinkcount.Thisoptionisneeded
whensearchingfilesystemsthatdonotfollowtheUnix
directorylinkconvention,suchasCDROMorMSDOS
filesystems,orAFSvolumemountpoints.Eachdirectoryona
normalUnixfilesystemhasatleast2hardlinks:itsnameand
its'.'entry.Additionally,itssubdirectories(ifany)eachhavea
'..'entrylinkedtothatdirectory.Whenfindisexamininga
directory,afterithasstatted2fewersubdirectoriesthanthe
directory'slinkcount,itknowsthattherestoftheentriesin
thedirectoryarenondirectories('leaf'filesinthedirectory
tree).Ifonlythefiles'namesneedtobeexamined,thereisno
needtostatthemthisgivesasignificantincreaseinsearch
speed.

Ifyouareusingastandardlinuxfilesystem,youshouldnot
needtousethisoption.

http://www.computerhope.com/unix/ufind.htm 8/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

regextypetype Changestheregularexpressionsyntaxunderstoodbyregex
andiregextestswhichoccurlateronthecommandline.
Currentlyimplementedtypesareemacs(thisisthedefault),
posixawk,posixbasic,posixegrepandposixextended.

Ifyou'reusingaspecificstyleofregularexpressionsyntax,
youmayneedtospecifythisoption.Otherwise,itshouldbe
unnecessary.

version,version Printthefindversionnumberandexit.

warn,nowarn Turnwarningmessagesonoroff.Thesewarningsapplyonly
tothecommandlineusage,nottoanyconditionsthatfind
mightencounterwhenitsearchesdirectories.Thedefault
behaviourcorrespondstowarnifstandardinputisatty,and
tonowarnotherwise.

xdev Don'tdescenddirectoriesonotherfilesystems.

Tests
Sometests,forexamplenewerXYandsamefile,allowcomparisonbetweenthefile
currentlybeingexaminedandsomereferencefilespecifiedonthecommandline.When
thesetestsareused,theinterpretationofthereferencefileisdeterminedbytheoptionsH,
LandPandanypreviousfollow,butthereferencefileisonlyexaminedonce,atthe
timethecommandlineisparsed.Ifthereferencefilecannotbeexamined(forexample,the
statsystemcallfailsforit),anerrormessageisissued,andfindexitswithanonzerostatus.

Wherenisusedasanumericargument,itcanbespecifiedas:

+n forgreaterthann

n forlessthann

http://www.computerhope.com/unix/ufind.htm 9/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

n forexactlyn.

Testsareasfollows:

aminn Returnstrueisafilewaslastaccessednminutesago.

anewerfile Returnstrueifafilewaslastaccessedmorerecentlythanfilewas
modified.IffileisasymboliclinkandtheHoptionortheLoption
isineffect,theaccesstimeofthefileitpointstoisalwaysused.

atimen Returnstrueifafilewaslastaccessedn*24hoursago.Whenfind
figuresouthowmany24hourperiodsagothefilewaslastaccessed,
anyfractionalpartisignored,sotomatchatime+1,afilehasto
havebeenaccessedatleasttwodaysago.

cminn Returnstrueifafile'sstatuswaslastchangednminutesago.

cnewerfile Returnstrueifafile'sstatuswaslastchangedmorerecentlythanfile
wasmodified.IffileisasymboliclinkandtheHoptionortheL
optionisineffect,thestatuschangetimeofthefileitpointstois
alwaysused.

ctimen Returnstrueifafile'sstatuswaslastchangedn*24hoursago.Seethe
commentsforatimetounderstandhowroundingaffectsthe
interpretationoffilestatuschangetimes.

empty Returnstrueifafileisempty(containsnothing)andiseitheraregular
fileoradirectory.

executable Matchesfileswhichareexecutableanddirectorieswhichare
searchable(inafilenameresolutionsense).Thistakesintoaccount
accesscontrollistsandotherpermissionsartefactswhichtheperm

http://www.computerhope.com/unix/ufind.htm 10/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

testignores.Thistestmakesuseoftheaccesssystemcall,andsocan
befooledbyNFSserverswhichdoUIDmapping(orrootsquashing),
sincemanysystemsimplementaccessintheclient'skernelandso
cannotmakeuseoftheUIDmappinginformationheldontheserver.
Becausethistestisbasedonlyontheresultoftheaccesssystemcall,
thereisnoguaranteethatafileforwhichthistestsucceedscan
actuallybeexecuted.

false Whenusedaspartofanexpression,falsealwaysevaluatesasfalse.

fstypetype Returnstrueifafileisonafilesystemoftypetype.Thevalid
filesystemtypesvaryamongdifferentversionsofUnixan
incompletelistoffilesystemtypesthatareacceptedonsomeversion
ofUnixoranotheris:ufs,4.2,4.3,nfs,tmp,mfs,S51K,S52K.You
canuseprintfwiththe%Fdirectivetoseethetypesofyour
filesystems.

gidn Returnstrueifafile'snumericgroupIDisn.

groupgname Returnstrueifafilebelongstogroupgname(numericgroupIDsare
allowed).

ilnamepattern Likelname,butthematchiscaseinsensitive.IftheLoptionorthe
followoptionisineffect,thistestreturnsfalseunlessthesymbolic
linkisbroken.

inamepattern Likename,butthematchiscaseinsensitive.Forexample,the
patterns'fo*'and'F??'matchthefilenames'Foo','FOO','foo','fOo',
etc.Inthesepatterns,unlikefilenameexpansionbytheshell,aninitial
'.'canbematchedby'*'.Thatis,findname*barwillmatchthefile
'.foobar'.Pleasenotethatyoushouldalwaysquotepatterns,otherwise
theshellwillexpandanywildcardcharactersinthem.

http://www.computerhope.com/unix/ufind.htm 11/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

inumn Returnstrueifafilehasinodenumbern.Itisnormallyeasiertouse
thesamefiletestinstead.

ipathpattern Behavesinthesamewayasiwholename.Thisoptionisdeprecated,
soyoushouldnolongeruseit.

iregexpattern Likeregex,butthematchiscaseinsensitive.

iwholename Likewholename,butthematchiscaseinsensitive.
pattern

linksn Returnstrueifafilehasnlinks.

lnamepattern Returnstrueifafileisasymboliclinkwhosecontentsmatchshell
patternpattern.Themetacharactersdonottreat'/'or'.'specially.If
theLoptionorthefollowoptionisineffect,thistestreturnsfalse
unlessthesymboliclinkisbroken.

mminn Returnstrueifthefile'sdatawaslastmodifiednminutesago.

mtimen Returnstrueifafile'sdatawaslastmodifiedn*24hoursago.Seethe
atimeoptiontounderstandhowroundingaffectstheinterpretationof
filemodificationtimes.

namepattern Returnstrueifthebaseofafilename(thepathwiththeleading
directoriesremoved)matchesshellpatternpattern.The
metacharacters('*','?',and'[]')matcha'.'atthestartofthebase
name.Toignoreadirectoryandthefilesunderit,usepruneseean
exampleinthedescriptionofpath.Bracesarenotrecognisedas
beingspecial,despitethefactthatsomeshellsincludingBashimbue
braceswithaspecialmeaninginshellpatterns.Thefilename
matchingisperformedwiththeuseofthefnmatchlibraryfunction.
Don'tforgettoenclosethepatterninquotesinordertoprotectitfrom
expansionbytheshell.
http://www.computerhope.com/unix/ufind.htm 12/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

newerfile Returnstrueifafilewasmodifiedmorerecentlythanthefilefile.If
fileisasymboliclinkandtheHoptionortheLoptionisineffect,
themodificationtimeofthefileitpointstoisalwaysused.

newerXY Comparesthetimestampofthecurrentfilewithreference.The
reference referenceargumentisnormallythenameofafile(andoneofits
timestampsisusedforthecomparison)butitmayalsobeastring
describinganabsolutetime.XandYareplaceholdersforother
letters,andtheselettersselectwhichtimebelongingtohowreference
isusedforthecomparison.

a Theaccesstimeofthefilereference

B Thebirthtimeofthefilereference

c Theinodestatuschangetimeofreference

m Themodificationtimeofthefilereference

t referenceisinterpreteddirectlyasatime

Somecombinationsareinvalidforexample,itisinvalidforXtobet.
Somecombinationsarenotimplementedonallsystemsforexample
Bisnotsupportedonallsystems.Ifaninvalidorunsupported
combinationofXYisspecified,afatalerrorresults.Time
specificationsareinterpretedasfortheargumenttothedoptionof
GNUdate.Ifyoutrytousethebirthtimeofareferencefile,andthe
birthtimecannotbedetermined,afatalerrormessageresults.Ifyou
specifyatestwhichreferstothebirthtimeoffilesbeingexamined,
thistestwillfailforanyfileswherethebirthtimeisunknown.

http://www.computerhope.com/unix/ufind.htm 13/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

nogroup Returnstueifnoexistinggroupcorrespondstofile'snumericgroup
ID.

nouser Returnstrueifnoexistingusercorrespondstofile'snumericuserID.

pathpattern Returnstrueifafilenamematchesshellpatternpattern.The
metacharactersdonottreat'/'or'.'speciallyso,forexample,

find.path"./sr*sc"

willprintanentryforadirectorycalled'./src/misc'(ifoneexists).To
ignoreawholedirectorytree,usepruneratherthancheckingevery
fileinthetree.Forexample,toskipthedirectory'src/emacs'andall
filesanddirectoriesunderit,andprintthenamesoftheotherfiles
found,dosomethinglikethis:

find.path./src/emacspruneoprint

Notethatthepatternmatchtestappliestothewholefilename,
startingfromoneofthestartpointsnamedonthecommandline.It
wouldonlymakesensetouseanabsolutepathnamehereifthe
relevantstartpointisalsoanabsolutepath.Thismeansthatthis
commandwillnevermatchanything:

findbarpath/foo/bar/myfileprint

ThepredicatepathisalsosupportedbyHPUXfindandwillbeina
forthcomingversionofthePOSIXstandard.
http://www.computerhope.com/unix/ufind.htm 14/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

permmode Returnstrueifafile'spermissionbitsareexactlymode(octalor
symbolic).Sinceanexactmatchisrequired,ifyouwanttousethis
formforsymbolicmodes,youmayhavetospecifyarathercomplex
modestring.Forexamplepermg=wwillonlymatchfileswhich
havemode0020(thatis,onesforwhichgroupwritepermissionisthe
onlypermissionset).Itismorelikelythatyouwillwanttousethe'/'
or''forms,forexamplepermg=w,whichmatchesanyfilewith
groupwritepermission.

permmode Returnstrueifallofthepermissionbitsofmodearesetforthefile.
Symbolicmodesareacceptedinthisform,andthisisusuallytheway
inwhichwouldwanttousethem.Youmustspecify'u','g'or'o'ifyou
useasymbolicmode.

perm/mode Returnstrueifanyofthepermissionbitsofmodearesetforthefile.
Symbolicmodesareacceptedinthisform.Youmustspecify'u','g'or
'o'ifyouuseasymbolicmode.Ifnopermissionbitsinmodeareset,
thistestmatchesanyfile.

perm+mode Deprecatedthisistheoldwayofsearchingforfileswithanyofthe
permissionbitsinmode.Youshoulduseperm/modeinstead.
Tryingtousethe'+'syntaxwithsymbolicmodeswillyield
unexpectedresults.

readable Matchesfileswhicharereadable.Thistakesintoaccountaccess
controllistsandotherpermissionsfactorswhichthepermtest
ignores.Thistestmakesuseoftheaccesssystemcall,andsocanbe
fooledbyNFSserverswhichdoUIDmapping(orrootsquashing),
sincemanysystemsimplementaccessintheclient'skernelandso
cannotmakeuseoftheUIDmappinginformationheldontheserver.

regexpattern Returnstrueifafilenamematchestheregularexpressionpattern.
Thisisamatchonthewholepath,notjustthefilename.Forexample,
http://www.computerhope.com/unix/ufind.htm 15/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

tomatchafilenamed'./fubar3',youcanusetheregularexpression
'.*bar.'or'.*b.*3',butnot'f.*r3'(becausethecompletepathdoesnot
beginwithanf).Theregularexpressionsunderstoodbyfindareby
BacktoTop
defaultEmacsregularexpressions,butthiscanbechangedwiththe
regextypeoption(seeabove).

samefilename Returnstrueifafilereferstothesameinodeasname.WhenLisin
effect,thiscanincludesymboliclinks.

size[ Returnstrueifafileusesnunitsofspaceonthedisk.Ifprecededbya
|+]n[cwbkMG] minussign(""),matchesfileswhichuselessspaceifprecededbya
plussign("+"),matchesfileswhichusemore.Thefollowingsuffixes
canbeusedtoabbreviateunits:

b for512byteblocks(thisisthedefaultifnosuffixis
used)

c forbytes

w fortwobytewords

k forKilobytes(unitsof1024bytes)

M forMegabytes(unitsof1048576bytes)

G forGigabytes(unitsof1073741824bytes)

Thesizedoesnotcountindirectblocks,butitdoescountblocksin
sparsefilesthatarenotactuallyallocated.Youshouldnotethatthe
'%k'and'%b'formatspecifiersofprintfhandlesparsefiles
differently.The'b'suffixalwaysdenotes512byteblocksandnever1
Kilobyteblocks,whichisdifferentthanthebehaviourofls.

http://www.computerhope.com/unix/ufind.htm 16/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

true Whenusedinanexpression,truealwaysreturnstrue.

typec Returnstrueifafileisoftypec:

b block(buffered)specialfiles

c character(unbuffered)specialfiles

d directories

p namedpipes(FIFOs)

f regularfiles

l symboliclinks.ThisisnevertrueiftheLoptionorthe
followoptionhasbeenspecified,unlessthesymboliclink
isbroken.Ifyouwanttosearchforsymboliclinkswhen
iLisineffect,usextype.

s sockets

D doors(aSolarisfiletype)

uidn Returnstrueifafile'snumericuserIDisn.

usedn Returnstrueifafilewaslastaccessedndaysafteritsstatuswaslast
changed.

useruname Returnstrueifafileisownedbyuseruname(numericuserIDsare
allowed).

wholename Functionallythesameaspath.Thisalternativeislessportablethan

http://www.computerhope.com/unix/ufind.htm 17/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

pattern path,howeverforgreatestcomplianceacrossdifferenttypesof
systems,youshouldusepathinstead.

writable Matchesfileswhicharewritable.Thistakesintoaccountaccess
controllistsandotherpermissionsfactorswhichthepermtest
ignores.Thistestmakesuseoftheaccesssystemcall,andsocanbe
fooledbyNFSserverswhichdoUIDmapping(orrootsquashing),
sincemanysystemsimplementaccessintheclient'skernelandso
cannotmakeuseoftheUIDmappinginformationheldontheserver.

xtypec Thesameastypeunlessthefileisasymboliclink.Forsymbolic
links:iftheHorPoptionwasspecified,returnstrueifthefileisa
linktoafileoftypeciftheLoptionhasbeengiven,returnstrueifc
is'l'.Inotherwords,forsymboliclinks,xtypechecksthetypeofthe
filethattypedoesnotcheck.

Actions

delete Deletematchedfilesreturnstrueifremoval
succeeded.Iftheremovalfailed,anerrormessageis
issued.Ifdeletefails,find'sexitstatuswillbe
nonzero(wheniteventuallyexits).Useofdelete
automaticallyturnsonthedepthoption.

Don'tforgetthatthefindcommandlineisevaluated
asanexpression,soputtingdeletefirstwillmake
findtrytodeleteeverythingbelowthestartingpoints
youspecified.Whentestingafindcommandlinethat
youlaterintendtousewithdelete,youshould
explicitlyspecifydepthinordertoavoidlater
surprises.Becausedeleteimpliesdepth,youcannot
usefullyusepruneanddeletetogether.

http://www.computerhope.com/unix/ufind.htm 18/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

execcommand Executecommandoneachmatchedfilereturnstrueif
0isreturnedastheexitstatusofcommand.All
followingargumentstofindaretakentobearguments
tothecommanduntilasemicolon('')isencountered.
Thestring'{}'isreplacedbythecurrentfilename
beingprocessedeverywhereitoccursinthearguments
tothecommand,notjustinargumentswhereitis
alone,asinsomeversionsoffind.Bothofthese
constructionsmightneedtobeescaped(witha'\')or
quotedtoprotectthemfromexpansionbytheshell.
Thespecifiedcommandisrunonceforeachmatched
file.Thecommandisexecutedinthestarting
directory.Thereareunavoidablesecurityproblems
surroundinguseofexecyoushouldusetheexecdir
optioninstead.

execcommand{}+ Thisvariantoftheexecactionrunsthespecified
commandontheselectedfiles,butthecommandline
isbuiltbyappendingeachselectedfilenameatthe
endthetotalnumberofinvocationsofthecommand
willbemuchlessthanthenumberofmatchedfiles.
Thecommandlineisbuiltinmuchthesamewaythat
xargsbuildsitscommandlines.Onlyoneinstanceof
'{}'isallowedwithinthecommand.Thecommandis
executedinthestartingdirectory.

execdircommand Likeexec,butthespecifiedcommandisrunfromthe
subdirectorycontainingthematchedfile,whichisnot
execdircommand{}+ normallythedirectoryinwhichyoustartedfind.This
amuchmoresecuremethodforinvokingcommands,
asitavoids"raceconditions"(wherethebehavioris
determinedbyanunpredictableorderofsystem
operations)duringresolutionofthepathstothe
matchedfiles.Aswiththeexecaction,the'+'formof
http://www.computerhope.com/unix/ufind.htm 19/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

execdirwillbuildacommandlinetoprocessmore
thanonematchedfile,butanygiveninvocationof
commandwillonlylistfilesthatexistinthesame
subdirectory.Ifyouusethisoption,youmustensure
thatyour$PATHenvironmentvariabledoesnot
reference'.'otherwise,anattackercanrunany
commandstheylikebyleavinganappropriately
namedfileinadirectoryinwhichyouwillrun
execdir.Thesameappliestohavingentriesin
$PATHwhichareemptyorwhicharenotabsolute
directorynames.

flsfile Returnstruebehaveslikels,butwritestofilelike
fprint.Theoutputfileisalwayscreated,evenifno
matchisfound.

fprintfile Returnstrueprintsthefullfilenameintofilefile.If
filedoesnotexistwhenfindisrun,itiscreatedifit
doesexist,itistruncated.Thefilenames
"/dev/stdout"and"/dev/stderr"arehandledspecially
theyrefertothestandardoutputandstandarderror
output,respectively.Theoutputfileisalwayscreated,
evenifthepredicateisnevermatched.

fprint0file Returnstruelikeprint0butwritestofilelike
fprint.Theoutputfileisalwayscreated,evenifno
matchisfound.

fprintffileformat Returnstruelikeprintf,butwritestofilelike
fprint.Theoutputfileisalwayscreated,evenifthe
predicateisnevermatched.

ls Returnstruelistscurrentfileinlsdilsformat(seels
fordetails)onstandardoutput.Theblockcountsareof
http://www.computerhope.com/unix/ufind.htm 20/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

1Kblocks,unlesstheenvironmentvariable
POSIXLY_CORRECTisset,inwhichcase512byte
blocksareused.

okcommand Likeexec,butaskstheuserfirst.Iftheuseragrees,
findrunsthecommand.Otherwiseitsimplyreturns
false.Ifthecommandisrun,itsstandardinputis
redirectedfrom/dev/null.

Theresponsetothepromptismatchedagainstapair
ofregularexpressionstodetermineifitisan
affirmativeornegativeresponse.Thisregular
expressionisobtainedfromthesystemifthe
'POSIXLY_CORRECT'environmentvariableisset,
orotherwisefromfind'smessagetranslations.Ifthe
systemhasnosuitabledefinition,find'sown
definitionwillbeused.Ineithercase,the
interpretationoftheregularexpressionitselfwillbe
affectedbytheenvironmentvariables'LC_CTYPE'
(characterclasses)and'LC_COLLATE'(character
rangesandequivalenceclasses).

okdircommand Likeexecdirbutaskstheuserfirstinthesameway
asforok.Iftheuserdoesnotagree,simplyreturns
false.Ifthecommandisrun,itsstandardinputis
redirectedfrom/dev/null.

print Returnstrueprintsthefullfilenameonthestandard
output,followedbyanewline.Ifyouarepipingthe
outputoffindintoanotherprogramandthereisthe
faintestpossibilitythatthefileswhichyouare
searchingformightcontainanewline,thenyou
shouldconsiderusingtheprint0optioninsteadof

http://www.computerhope.com/unix/ufind.htm 21/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

print.

print0 Returnstrueprintsthefullfilenameonthestandard
output,followedbyanullcharacter(insteadofthe
newlinecharacterthatprintuses).Thisallowsfile
namesthatcontainnewlinesorothertypesofwhite
spacetobecorrectlyinterpretedbyprogramsthat
processthefindoutput.Thisoptioncorrespondstothe
0optionofxargs.

printfformat Returnstrueprintsformatonthestandardoutput,
interpreting'\'escapesand'%'directives.Fieldwidths
andprecisionscanbespecifiedaswiththe'printf'C
function.Pleasenotethatmanyofthefieldsare
printedas%sratherthan%d,andthismaymeanthat
flagsdon'tworkasyoumightexpect.Thisalsomeans
thatthe''flagdoeswork(itforcesfieldstobeleft
aligned).Unlikeprint,printfdoesnotaddanewline
attheendofthestring.Theescapesanddirectivesare:

\a Alarmbell.

\b Backspace.

\c Stopprintingusingformat
immediatelyandflushtheremaining
output.

\f Formfeed.

\n Newline.

\r Carriagereturn.

http://www.computerhope.com/unix/ufind.htm 22/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

\t Horizontaltab.

\v Verticaltab.

\0 TheASCIINULcharacter.

\\ Aliteralbackslash('\').

\NNN ThecharacterwhoseASCIIcodeis
NNN(whereNNNisanoctalvalue).

A'\'characterfollowedbyanyothercharacteris
treatedasanordinarycharacter,sotheybothare
printed.

%% Aliteralpercentsign.

%a Thefile'slastaccesstimeintheformat
returnedbytheCctimefunction.

%Ak Thefile'slastaccesstimeintheformat
specifiedbyk,whichiseither'@'ora
directiveoftheC'strftime'function.
Thepossiblevaluesforkarelisted
belowsomeofthemmightnotbe
availableonallsystems,dueto
differencesinstrftimebetween
systems.

Valuesforkcanbeoneofthe
following:

http://www.computerhope.com/unix/ufind.htm 23/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

@ secondssinceJan.1,1970,
00:00GMT,withfractional
part.

Timefields:

H hour(00..23)

I hour(01..12)

k hour(0..23)

l hour(1..12)

M minute(00..59)

p locale'sAMorPM

r time,12hour(hh:mm:ss
[AP]M)

S Second(00.00..61.00).
Thereisafractionalpart.

T time,24hour(hh:mm:ss)

+ Dateandtime,separatedby
'+',forexample'200404
28+22:22:05.0'.Thisisa
GNUextension.Thetime
isgiveninthecurrent
timezone(whichmaybe
affectedbysettingtheTZ

http://www.computerhope.com/unix/ufind.htm 24/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

environmentvariable).The
secondsfieldincludesa
fractionalpart.

X locale'stimerepresentation
(H:M:S)

Z timezone(e.g.,EDT),or
nothingifnotimezoneis
determinable

Datefields:

a locale'sabbreviated
weekdayname(Sun..Sat)

A locale'sfullweekdayname,
variablelength
(Sunday..Saturday)

b locale'sabbreviatedmonth
name(Jan..Dec)

B locale'sfullmonthname,
variablelength
(January..December)

c locale'sdateandtime(Sat
Nov0412:02:33EST
1989).Theformatisthe
sameasforctimeandsoto
preservecompatibilitywith
thatformat,thereisno
http://www.computerhope.com/unix/ufind.htm 25/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

fractionalpartinthe
secondsfield.

d dayofmonth(01..31)

D date(mm/dd/yy)

h sameasb

j dayofyear(001..366)

m month(01..12)

U weeknumberofyearwith
Sundayasfirstdayofweek
(00..53)

w dayofweek(0..6)

W weeknumberofyearwith
Mondayasfirstdayof
week(00..53)

x locale'sdaterepresentation
(mm/dd/yy)

y lasttwodigitsofyear
(00..99)

Y year(1970..)

%b Theamountofdiskspaceusedforthis
filein512byteblocks.Sincedisk
http://www.computerhope.com/unix/ufind.htm 26/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

spaceisallocatedinmultiplesofthe
filesystemblocksizethisisusually
greaterthan%s/512,butitcanalsobe
smallerifthefileisasparsefile.

%c File'slaststatuschangetimeinthe
formatreturnedbytheC'ctime'
function.

%Ck File'slaststatuschangetimeinthe
formatspecifiedbyk,whichisthe
sameasfor%A.

%d File'sdepthinthedirectorytree0
meansthefileisacommandline
argument.

%D Thedevicenumberonwhichthefile
exists(thest_devfieldofstructstat),
indecimal.

%f File'snamewithanyleadingdirectories
removed(onlythelastelement).

%F Typeofthefilesystemthefileison
thisvaluecanbeusedforfstype.

%g File'sgroupname,ornumericgroupID
ifthegrouphasnoname.

%G File'snumericgroupID.

%h Leadingdirectoriesoffile'sname(all

http://www.computerhope.com/unix/ufind.htm 27/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

butthelastelement).Ifthefilename
containsnoslashes(sinceitisinthe
currentdirectory)the%hspecifier
expandsto".".

%H Commandlineargumentunderwhich
filewasfound.

%i File'sinodenumber(indecimal).

%k Theamountofdiskspaceusedforthis
filein1Kblocks.Sincediskspaceis
allocatedinmultiplesofthefilesystem
blocksizethisisusuallygreaterthan
%s/1024,butitcanalsobesmallerif
thefileisasparsefile.

%l Objectofsymboliclink(emptystring
iffileisnotasymboliclink).

%m File'spermissionbits(inoctal).This
optionusesthe'traditional'numbers
whichmostUniximplementationsuse,
butifyourparticularimplementation
usesanunusualorderingofoctal
permissionsbits,youwillseea
differencebetweentheactualvalueof
thefile'smodeandtheoutputof%m.
Normallyyouwillwanttohavea
leadingzeroonthisnumber,andtodo
this,youshouldusethe#flag(asin,
forexample,'%#m').

%M File'spermissions(insymbolicform,

http://www.computerhope.com/unix/ufind.htm 28/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

asforls).

%n Numberofhardlinkstofile.

%p File'sname.

%P File'snamewiththenameofthe
commandlineargumentunderwhichit
wasfoundremoved.

%s File'ssizeinbytes.

%S File'ssparseness.Thisiscalculatedas
(BLOCKSIZE*st_blocks/st_size).
Theexactvalueyouwillgetforan
ordinaryfileofacertainlengthis
systemdependent.However,normally
sparsefileswillhavevalueslessthan
1.0,andfileswhichuseindirectblocks
mayhaveavaluewhichisgreaterthan
1.0.ThevalueusedforBLOCKSIZEis
systemdependent,butisusually512
bytes.Ifthefilesizeiszero,thevalue
printedisundefined.Onsystemswhich
lacksupportforst_blocks,afile's
sparsenessisassumedtobe1.0.

%t File'slastmodificationtimeinthe
formatreturnedbytheC'ctime'
function.

%Tk File'slastmodificationtimeinthe
formatspecifiedbyk,whichisthe
sameasfor%A.
http://www.computerhope.com/unix/ufind.htm 29/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

%u File'susername,ornumericuserIDif
theuserhasnoname.

%U File'snumericuserID.

%y File'stype(likeinlsl).U=unknown
type(althoughthisshouldn'thappen)

%Y File'stype(like%y),plusfollow
symlinks:L=loop,N=nonexistent

A'%'characterfollowedbyanyothercharacteris
discarded,buttheothercharacterisprinted(butdon't
relyonthis,asfurtherformatcharactersmaybe
introduced).A'%'attheendoftheformatargument
causesundefinedbehavioursincethereisnofollowing
character.Insomelocales,itmayhideyourdoorkeys,
whileinothersitmayremovethefinalpagefromthe
novelyouarereading.

The%mand%ddirectivessupportthe#,0and+
flags,buttheotherdirectivesdonot,eveniftheyprint
numbers.Numericdirectivesthatdonotsupportthese
flagsincludeG,U,b,D,kandn.The''formatflagis
supportedandchangesthealignmentofafieldfrom
rightjustified(whichisthedefault)toleftjustified.

prune Trueifthefileisadirectory,donotdescendintoit.
Ifdepthisgiven,falsenoeffect.Becausedelete
impliesdepth,youcannotusefullyusepruneand
deletetogether.

http://www.computerhope.com/unix/ufind.htm 30/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

quit Exitimmediately.Nochildprocesseswillbeleft
running,butnomorepathsspecifiedonthecommand
linewillbeprocessed.Forexample,find/tmp/foo
/tmp/barprintquitwillprintonly/tmp/foo.Any
commandlineswhichhavebeenbuiltupwith
execdir...{}+willbeinvokedbeforefindexits.The
exitstatusmayormaynotbezero,dependingon
whetheranerrorhasalreadyoccurred.

HandlingUnusualFilenames
Manyoftheactionsoffindresultintheprintingofdatawhichisunderthecontrolofother
users.Thisincludesfilenames,sizes,modificationtimesandsoforth.Filenamesarea
potentialproblemsincetheycancontainanycharacterexcept'\0'and'/'.Unusualcharacters
infilenamescandounexpectedandoftenundesirablethingstoyourterminal(forexample,
changingthesettingsofyourfunctionkeysonsometerminals).Unusualcharactersare
handleddifferentlybyvariousactions,asdescribedbelow:

print0,fprint0 Alwaysprinttheexactfilename,unchanged,evenifthe
outputisgoingtoaterminal.

ls,fls Unusualcharactersarealwaysescaped.Whitespace,
backslash,anddoublequotecharactersareprintedusingC
styleescaping(forexample'\f','\"').Otherunusual
charactersareprintedusinganoctalescape.Otherprintable
characters(forlsandflsthesearethecharactersbetween
octal041and0176)areprintedasis.

printf,fprintf Iftheoutputisnotgoingtoaterminal,itisprintedasis.
Otherwise,theresultdependsonwhichdirectiveisinuse.
Thedirectives%D,%F,%g,%G,%H,%Y,and%y
expandtovalueswhicharenotundercontroloffiles'

http://www.computerhope.com/unix/ufind.htm 31/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

owners,andsoareprintedasis.Thedirectives%a,%b,
%c,%d,%i,%k,%m,%M,%n,%s,%t,%uand%U
havevalueswhichareunderthecontroloffiles'ownersbut
whichcannotbeusedtosendarbitrarydatatotheterminal,
andsotheseareprintedasis.Thedirectives%f,%h,%l,
%pand%Parequoted.Thisquotingisperformedinthe
samewayasforGNUls.Thisisnotthesamequoting
mechanismastheoneusedforlsandfls.Ifyouareableto
decidewhatformattousefortheoutputoffindthenitis
normallybettertouse'\0'asaterminatorthantouse
newline,asfilenamescancontainwhitespaceandnewline
characters.Thesettingofthe'LC_CTYPE'environment
variableisusedtodeterminewhichcharactersneedtobe
quoted.

print,fprint Quotingishandledinthesamewayasforprintfand
fprintf.Ifyouareusingfindinascriptorinasituation
wherethematchedfilesmighthavearbitrarynames,you
shouldconsiderusingprint0insteadofprint.

Theokandokdiractionsprintthecurrentfilenameasis.

Operators
Thefollowingfindoperatorsarelistedinorderofincreasingprecedence:

(expr) Forceprecedence.Sinceparenthesesarespecialtotheshell,
youwillnormallyneedtoquotethem.Forinstance,youwill
probablyneedtospecify'\(...\)'insteadof'(...)'.

!expr Returnstrueifexprisfalse.Thischaracterwillalsousually
needprotectionfrominterpretationbytheshell.
http://www.computerhope.com/unix/ufind.htm 32/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

notexpr Sameas!expr,butnotPOSIXcompliant.

expr1expr2 Twoexpressionsinarowaretakentobejoinedwithan
implied"and"inotherwords,expr2isnotevaluatedif
expr1isfalse.

expr1aexpr2 Sameasexpr1expr2.

expr1andexpr2 Sameasexpr1expr2,butnotPOSIXcompliant.

expr1oexpr2 BooleanORinotherwords,expr2isnotevaluatedifexpr1
istrue.

expr1orexpr2 Sameasexpr1oexpr2,butnotPOSIXcompliant.

expr1,expr2 Separatingtwoexpressionswithacommatreatsthemasa
list:bothexpr1andexpr2arealwaysevaluated.Thevalueof
expr1isdiscardedinthereturnvaluethevalueofthelistis
thevalueofexpr2.Thecommaoperatorcanbeusefulfor
searchingforseveraldifferenttypesofthing,buttraversing
thefilesystemhierarchyonlyonce.Thefprintfactioncan
beusedtolistthevariousmatcheditemsintoseveral
differentoutputfiles.

EnvironmentVariables

LANG Providesadefaultvaluefortheinternationalizationvariables
thatareunsetornull.

LC_ALL Ifsettoanonemptystringvalue,thisvariable'svalue
overridesthevaluesofalltheotherinternationalization

http://www.computerhope.com/unix/ufind.htm 33/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

variables.

LC_COLLATE ThePOSIXstandardspecifiesthatthisvariableaffectthe
patternmatchingtobeusedforthenameoption.GNUfind
usesthefnmatchlibraryfunction,andsosupportfor
'LC_COLLATE'dependsonthesystemlibrary.Thisvariable
alsoaffectstheinterpretationoftheresponsetookwhilethe
'LC_MESSAGES'variableselectstheactualpatternusedto
interprettheresponsetook,theinterpretationofanybracket
expressionsinthepatternwillbeaffectedby
'LC_COLLATE'.

LC_CTYPE Thisvariableaffectsthetreatmentofcharacterclassesusedin
regularexpressionsandalsowiththenametest,ifthe
system'sfnmatchlibraryfunctionsupportsthis.Thisvariable
alsoaffectstheinterpretationofanycharacterclassesinthe
regularexpressionsusedtointerprettheresponsetothe
promptissuedbyok.The'LC_CTYPE'environment
variablewillalsoaffectwhichcharactersareconsideredtobe
unprintablewhenfilenamesareprinted.

LC_MESSAGES Determinesthelocaletobeusedforinternationalised
messages.Ifthe'POSIXLY_CORRECT'environment
variableisset,thisalsodeterminestheinterpretationofthe
responsetothepromptmadebytheokaction.

NLSPATH Determinesthelocationoftheinternationalisationmessage
catalogues.

PATH Affectsthedirectorieswhicharesearchedtofindthe
executablesinvokedbyexec,execdir,okandokdir.

POSIXLY_CORRECT Determinestheblocksizeusedbylsandfls.If
POSIXLY_CORRECTisset,blocksareunitsof512bytes.
http://www.computerhope.com/unix/ufind.htm 34/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

Otherwisetheyareunitsof1024bytes.

Settingthisvariablealsoturnsoffwarningmessages(thatis,
impliesnowarn)bydefault,becausePOSIXrequiresthat
apartfromtheoutputforok,allmessagesprintedonstderr
arediagnosticsandmustresultinanonzeroexitstatus.

WhenPOSIXLY_CORRECTisnotset,perm+zzzis
treatedjustlikeperm/zzzif+zzzisnotavalidsymbolic
mode.WhenPOSIXLY_CORRECTisset,suchconstructs
aretreatedasanerror.

WhenPOSIXLY_CORRECTisset,theresponsetothe
promptmadebytheokactionisinterpretedaccordingtothe
system'smessagecatalogue,asopposedtoaccordingtofind's
ownmessagetranslations.

TZ Affectsthetimezoneusedforsomeofthetimerelatedformat
directivesofprintfandfprintf.

Examples

find

Whenusinglinux,runningthefindcommandwithoutanyoptionswilllocateandprinta
listofeveryfileinandbeneaththecurrentdirectory.Thisincludesallfilesinall
subdirectoriesofthecurrentdirectory.

find.

Sameastheabovecommand.The"."explicitlytellsfindthatyouwantthesearchtobegin

http://www.computerhope.com/unix/ufind.htm 35/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

inthecurrentdirectory.

find./home/jeff/home/stacy

Locateandprintallfilesanddirectoriesinandbeneaththreedifferentstartingdirectories:
thecurrentdirectory,/home/jeff,and/home/stacy.

find/usr/bin/usr/libname'*zip*'

Locateandprintallfilesanddirectoriesinandbeneatheitherofthedirectories/usr/bin
and/usr/libwhichcontainsthetext"zip"anywhereinthefileordirectoryname.

find/home/jeff/fruit|grep'apple'

Thiscommandtellsfindtolocateandprintacompletelistofallfilesinandbeneaththe
directory/home/jeff/fruit,andtopipethislistingtogrep,whichfiltersoutanyfilename
whichdoesnotcontainthetext"apple".

find.name'apple'

Locateandprintalistofanyfileinorbelowthecurrentdirectorywhosenameisexactly
"apple",alllowercaseletters.

find.iname'apple'

Locateandprintalistofanyfileinorbelowthecurrentdirectorywhosenameis"apple",
butmatchtheletterscaseinsensitively.Therefore,filesordirectoriesnamed"Apple",

http://www.computerhope.com/unix/ufind.htm 36/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

"ApplE",and"ApPLe"willallbelistedbythiscommand.

find.name'apple'typef

Locateandprintalistoffilesinorbelowthecurrentdirectorywhosenameis"apple"do
notdisplaydirectories,sockets,orothernonregularfiletypes.

find.name'apple'typed

Locateaprintalistofdirectoriesinorbelowthecurrentdirectorywhosenameis"apple"
donotdisplayregularfiles,orfiletypesotherthandirectoryentries.

find.groupdev

Locateandprintalistofanyfileinorbelowthecurrentdirectorywhoseowninggroupis
thedevgroup.

find.L

Locateandprintalistofanyfileinorbelowthecurrentdirectory,andfollowsymbolic
links.Inotherwords,displayinformationaboutthefileasymboliclinklinksto,ratherthan
informationaboutthesymlinkitself.

find.atime+1

Locateandprintalistofanyfileinorbelowthecurrentdirectorythatwaslastaccessed
morethan1dayago.

http://www.computerhope.com/unix/ufind.htm 37/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

find.atime1

Locateandprintalistofanyfileinorbelowthecurrentdirectorythatwaslastaccessed
lessthan1dayago.

find.amin+5

Locateandprintalistofanyfileinorbelowthecurrentdirectorythatwasmodifiedmore
than5minutesago.

find.amin5

Locateandprintalistofanyfileinorbelowthecurrentdirectorythatwasmodifiedfewer
than5minutesago.

find.perm754

Locateandprintalistofanyfileinorbelowthecurrentdirectorywhoseoctalpermission
bitsare755(usercanread,write,andexecuteowninggroupmemberscanreadand
executeotherscanreadonly).Formoreinformationaboutpermissionbits,seechmod.

find.permu=rwx,g=rx,o=r

Sameastheabovecommand,butusesasymbolicrepresentationofthepermissionbits.
Notethatthesymbolicnotationusesacommaseparatorandcontainsnospaces.

find.size+1Mtypef
http://www.computerhope.com/unix/ufind.htm 38/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

Locateandprintalistofanyregularfileinorbelowthecurrentdirectorywhosesizeis
greaterthan1megabyte.

find.size5Gtypef

Locateandprintalistofanyregularfileinorbelowthecurrentdirectorywhosesizeisless
than5gigabytes.

find.userjeff

Locateandprintalistofanyfileordirectoryinorbelowthecurrentdirectoryownedby
theuserjeff.

find.size+1Gexecmv'{}'~/bigfiles\;

Locateanyfilesinorbelowthecurrentdirectorywhosesizeisgreaterthan1gigabyte,and
executethemvcommandonthem,movingthemintothedirectorybigfilesinyourhome
directory.The{}indicateswhereinthecommandthenameofthematchedfileshouldbe
placeditmustbeenclosedinquotestoprotectitfrombeingmisinterpretedbytheshell.
Similarly,thesemicolonwhichendsthecommandmustbeescapedwithabackslash("\").

find.size+1Gprint0|xargs0I'{}'mv'{}'~/bigfiles

Locateanyfilesinorbelowthecurrentdirectorywhosesizeisgreaterthan1gigabyte,then
pipethatlisttothexargscommand,whichusesthemvcommandtomoveeachoneof
thosefilesintothedirectorybigfilesinyourhomedirectory.Thisissimilartotheabove
command,butbetterforseveralreasons.First,itusestheprint0optiontotellfindto

http://www.computerhope.com/unix/ufind.htm 39/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

createitslistseparatingeachfilenamewithanullcharacterratherthananewlinethis
makesthelistdifficultforahumantoread,buthastheadvantageofmakingiteasierfor
anotherprogramtoparse.Youshouldalwaysuseprint0whenpipingoutputtoxargs.

Usingxargstoexecutecommandsoneveryfilefoundisgenerallybetterthanusingfind's
execoptionbecauseofthemoreefficientwayxargsthreadseachindividualcommandthat
itspawns.

The0argumenttoxargstellsittoexpectthenullcharacterasthefilenameseparator
(whichwespecifiedwithfind'sprint0option).

TheI'{}'optiontellsxargstoreplace"{}"withthenameofeachfileitfinds.Wethen
formourcommandusing{}wherewewantthefilenametoappear.Weencloseitinsingle
quotestoprotectitfromtheshell.

xargsdoesnotexpectasemicolonattheendofthecommand,unlikefindexec,soitisnot
includedinthiscommand.

find.size+1Gokmv'{}'~/bigfiles\;

Usingokisthesameasusingexec,butyouwillbeaskedforconfirmationbeforeeach
commandisexecuted.

find.name'*.jpg'oname'*.gif'

Locateanyfilesinorbelowthecurrentdirectorywhosesuffixis".jpg"or".gif".Theo
optionfunctionsasabooleanORoperatorifeitheroftheconditionsaretrue,thefilewill
beincludedinthelist.

find.maxdepth2name'*.jpg'

http://www.computerhope.com/unix/ufind.htm 40/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

Locateanyfilesinorbelowthecurrentdirectorywhosesuffixis".jpg",butlimit
subdirectorytraversalto2levelsbeneaththecurrentdirectory.Anysubdirectories3or
morelevelsdeepwillnotbesearched.

find.!name'*.jpg'

Locateanyfilesinorbelowthecurrentdirectorywhosesuffixisnot".jpg".The
exclamationmark("!")functionsasabooleanNOToperatoritlistsonlyfilesforwhich
theconditionisfalse.

find/tmpnamecoretypefprint0|xargs0/bin/rmf

Findfilesnamedcoreinorbelowthedirectory/tmpanddeletethem.Thenametest
comesbeforethetypetestinordertoavoidhavingtocallstatoneveryfile.

find$HOMEmtime0

Searchforfilesinyourhomedirectorywhichhavebeenmodifiedinthelasttwentyfour
hours.Thiscommandworksthiswaybecausethetimesinceeachfilewaslastmodifiedis
dividedby24hoursandanyremainderisdiscarded.Thatmeansthattomatchmtime0,a
filewillhavetohaveamodificationinthepastwhichislessthan24hoursago.

find/sbin/usr/sbinexecutable!readable

Searchforfilesinyoursuperuserbinarydirectories,/sbinand/usr/sbin,whichare
executablebutnotreadable.

SuppressingErrorMessagesWhenUsingfind
http://www.computerhope.com/unix/ufind.htm 41/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

Onelasttipforusingfind:youwillreceiveanerrormessageiffindencountersafileor
directoryyoudon'thaveaccesstoview.Theerrormessagewilllooklikethis:

find:`./tmp/sysfilePKdhtXMmr18n':Permissiondenied

Youmightnotwantthesemessagesinyouroutputtheycanmakeitdifficulttoparseyour
actualfindresults.

Fortheseexamples,we'llassumeyou'reusingbashasyourshell,whichisthedefault
underlinux.Let'ssayyourcommandisthissimpleone:

find.

Iftheresultsofthiscommandaregivingyou"Permissiondenied"errors,thesimplestway
tofilterthemoutistosendthemallto/dev/null,whichisthedeviceonlinuxwhichpoints
tonowhere.Yourcommandwouldlooklikethis:

find.2>/dev/null

Here,2>isaspecialoperatorinbashwhichmeans"redirectstandarderror".Thiswill
effectivelyhideallerrormessagesfromfind'soutput.

Youmightnotwanttohideeveryerrormessage,though.Whatifthere'sanothererrorof
somekind?Youdon'twanttosuppressthosemessagestoo.Inthatcase,youcanusethis
commandinstead:

find.2>&1|grepv'Permissiondenied'

Here,2>tellsbashtoredirectstandarderror,and&1tellsittousestandardoutputasthe
destination.Thisredirectsallerrormessagesissuedbyfindtostandardoutputthiswill
http://www.computerhope.com/unix/ufind.htm 42/43
3/5/2016 LinuxandUnixfindcommandhelpandexamples

lookthesameonyourterminalscreen,butbymergingthemwithstandardoutput,wehave
madethemfilterablebygrep.Sowethenpipetheoutputoffindtogrep,whichmatches
theinverse(v)ofourstring,'Permissiondenied'.Theresultisthatitdisplaysanyline
whichdoesnotcontainthatstring.Thisallowsyoutoviewyourresultswithoutanypesky
"Permissiondenied"errormessages.

Relatedcommands
chmodChangethepermissionsoffilesordirectories.
cpioCopyfilestoorfromarchives.
locateSearchalocaldatabasetofindfilesbyname.
lsListthecontentsofadirectoryordirectories.
shTheBourneshellcommandinterpreter.
whereisLocatethebinary,source,andmanualpagefilesforacommand.
whichLocatethebinaryofacommand.
xargsBuildandexecutecomplexcommands,andexecutethemonmultiplefiles.

2016ComputerHope
LegalDisclaimerPrivacyStatement

http://www.computerhope.com/unix/ufind.htm 43/43

Anda mungkin juga menyukai