Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

11/22/14

10 Xargs Command Examples in Linux / UNIX

Home
FreeeBook
Contact
About
StartHere

10XargsCommandExamplesinLinux/UNIX
byHimanshuAroraonDecember26,2013
36

Tweet

60

Thexargscommandisextremelyusefulwhenwecombineitwithothercommands.
Thistutorialsexplainstheusageofxargscommandusingfewsimpleexamples.
Theseexamplewillhelpyouunderstandthebasicsofhowxargscommandworks.But,onceyouunderstand
theseconcepts,youcancomeupwithyourowncleverexamplesofxargstosolvevariouscommandline
problems.
Syntaxofxargs(fromthemanpage):
xargs[0prtx][Eeofstr][e[eofstr]][eof[=eofstr]][null][ddelimiter][delimiterdelimiter][I
replacestr][i[replacestr]][replace[=replacestr]][l[maxlines]][Lmaxlines][maxlines[=max
lines]][nmaxargs][maxargs=maxargs][smaxchars][maxchars=maxchars][Pmaxprocs]
[maxprocs=maxprocs][interactive][verbose][exit][norunifempty][argfile=file][
showlimits][version][help][command[initialarguments]]

1.XargsBasicExample
Thexargscommand(bydefault)expectstheinputfromstdin,andexecutes/bin/echocommandovertheinput.
Thefollowingiswhathappenswhenyouexecutexargswithoutanyargument,orwhenyouexecuteitwithout
combiningwithanyothercommands.
Whenyoutypexargswithoutanyargument,itwillpromptyoutoentertheinputthroughstdin:

www.thegeekstuff.com/2013/12/xargs-examples/

1/11

11/22/14

10 Xargs Command Examples in Linux / UNIX

$ xargs
Hi,
Welcome to TGS.

Afteryoutypesomething,pressctrl+d,whichwillechothestringbacktoyouonstdoutasshownbelow.
$ xargs
Hi,
Welcome to TGS.Hi, Welcome to TGS.

2.SpecifyDelimiterUsingdoption
Delimiterscanbeappliedsothateachcharacterintheinputistakenliterallyusingdoptioninxargs.
Inthepreviousexample,eventhoughtheinputcontaineda\n(newline)afterHi,buttheechoedoutputdidnot
containthenewline\n.So,theoutputinthepreviousexamplewascombinedintoasingleline.
Inthefollowingexample,whenyouusethed\n,itwillpreservenewlinedelimiterintheoutput,anddisplaythe
outputexactlyasitwastyped.
$ xargs -d\n
Hi,
Welcome to TGS.

Afteryoutypetheabove,pressctrl+d,whichwillechothestringbacktoyouonstdoutasshownbelow.But,this
timeitwillpreservethenewline.
$ xargs -d\n
Hi,
Welcome to TGS.Hi,
Welcome to TGS.

3.LimitOutputPerLineUsingnOption
Bydefaultasexplainedearlier,xargsdisplayswhatevercomestoitsstdinasshownbelow.
$ echo a b c d e f| xargs
abcdef

But,theoutputofthexargscommandcanbesplitintomultiplelinesusingnoption.
Inthefollowingexample,weusedn3,whichwilldisplayonly3itemsperlineinthexargsoutput.
$ echo a b c d e f| xargs -n 3
abc

www.thegeekstuff.com/2013/12/xargs-examples/

2/11

11/22/14

10 Xargs Command Examples in Linux / UNIX

def

Inthesameway,youcanalsosplittheoutputwith2itemsperlineasshownbelowusingn2.
$ echo a b c d e f| xargs -n 2
ab
cd
ef

4.PromptUserBeforeExecutionusingpoption
Usingoptionp,youcanconfirmtheexecutionofthexargscommandfromtheuser.
Consideringthepreviousexample,ifwewanttoconfirmeachexecutionofthe/bin/echocommandbytheuser,
usethepoptionalongwithnoptionasshownbelow.
$ echo a b c d e f| xargs -p -n 3
/bin/echo a b c ?...y
/bin/echo d e f ?...a b c
y
def

Inthefollowingoutput,Isaidntoalltheechooutput.So,xargsdidnotexecuteanything.
$ echo a b c d e f| xargs -p -n 3
/bin/echo a b c ?...n
/bin/echo d e f ?...n
/bin/echo ?...n

Note:Thisishelpfulwhenyouarecombiningxargswithcommandsthataredisruptivelikerm.Inthosecases,
youmaywanttoseewhatxargsdoes.

5.AvoidDefault/bin/echoforBlankInputUsingrOption
Whenthereisablankinput(i.enoinputwasgiventoxargscommand),itwillexecutea/bin/echocommand
whichwilldisplayanewlineasshownbelow.
$ xargs -p

Pressctrldaftertypingxargsp,whichwillindicatethatitexecuteda/bin/echoasshownbelow.
$ xargs -p

/bin/echo ?...y

6.PrinttheCommandAlongwithOutputUsingtOption
Inthefollowingexample,typeabcdastheinputforthexargstcommand.
$ xargs -t
abcd

Pressctrldtocompletetheabovexargstcommand,whichwilldisplaythecommandthatxargsreallyexecutes
beforedisplayingtheoutput.Inthiscase,thecommandthatxargsexecutesis/bin/echoabcd,whichisdisplayed
here.
$ xargs -t
abcd
/bin/echo abcd

www.thegeekstuff.com/2013/12/xargs-examples/

3/11

11/22/14

10 Xargs Command Examples in Linux / UNIX

abcd

7.CombineXargswithFindCommand
Itisoneofthemostimportantusageofxargscommand.Whenyouneedtofindcertaintypeoffilesandperform
certainactionsonthem(mostpopularbeingthedeleteaction).
Thexargscommandisveryeffectivewhenwecombinewithothercommands.
Inthefollowingexample,wetooktheoutputofthefindcommand,andpasseditasinputtothexargscommand.
But,insteadofexecutingthedefault/bin/echocommand,weareinstructingxargscommandtoexecutethermrm
commandontheinput.
So,inthisexample,theoutputofthefindcommandisallthefileswith*.cextension,whichisgivenasinputto
thexargscommand,whichinturnexecutermrfcommandonallthe*.cfiles.
$ ls
one.c one.h two.c two.h
$ find . -name "*.c" | xargs rm -rf
$ ls
one.h two.h

8.DeleteFilesthathasWhitespaceintheFilename
Soweseethatdespiteofrunningthermcommandonthe.cfilesinthisdirectory,thefileTheGeekStuff.cwas
notdeleted.Thisisbecausethisfilecontainswhitespacecharactersinitsname.
Asshowninthefollowingexample,itdeletedallthefileswiththe*.cextensionexceptone.i.ethefilethathas
whitespaceinthefilename(i.eTheGeekStuff.c)wasnotdeletedbythermcommand.
$ touch "The Geek Stuff.c"
$ ls
one.c one.h two.c two.h The Geek Stuff.c
$ find . -name "*.c" | xargs rm -rf
$ ls
one.h two.h The Geek Stuff.c

Inthissituation,usetheprint0optionwithfindcommandand0optionwithxargscommandtodeletefiles
includingthosethathasspaceinthefilenamesasshownbelow.
$ ls
one.c one.h two.c two.h The Geek Stuff.c
$ find . -name "*.c" -print0 | xargs -0 rm -rf
$ ls
one.h two.h

9.DisplaySystemLimitsonxargsusingshowlimitsoption
Seetheexamplebelow:
ThefollowingexampledisplaysallthelimitssetbytheOSthatwillhaveanimpactonthewayhowxargs
commandworks.
$ xargs --show-limits

www.thegeekstuff.com/2013/12/xargs-examples/

4/11

11/22/14

10 Xargs Command Examples in Linux / UNIX

Your environment variables take up 1203 bytes


POSIX upper limit on argument length (this system): 2093901
POSIX smallest allowable upper limit on argument length (all systems): 4096
Maximum length of command we could actually use: 2092698
Size of command buffer we are actually using: 131072
Execution of xargs will continue now, and it will try to read its input and
run commands; if this is not what you wanted to happen, please type the
end-of-file keystroke.
Warning: /bin/echo will be run at least once. If you do not want that to happen,
then press the interrupt keystroke

10.CombineXargswithGrepcommand
Thexargscommandcanbecombinedwithgrepcommandtofilterparticularfilesfromthesearchresultsofthe
findcommand.
Inthefollowingexample,findcommandprovidedallthe.cfilesasinputtoxargs.
Thexargscommandexecutesthegrepcommandtofindallthefiles(amongthefilesprovidedbyfindcommand)
thatcontainedastringstdlib.h.
$ find . -name '*.c' | xargs grep 'stdlib.h'
./tgsthreads.c:#include
./valgrind.c:#include
./direntry.c:#include
./xvirus.c:#include
./temp.c:#include
...
...
...
36

Tweet

60

Like

31

>Addyourcomment

Linuxprovidesseveralpowerfuladministrativetoolsandutilitieswhichwillhelp
youtomanageyoursystemseffectively.Ifyoudontknowwhatthesetoolsareandhowtousethem,youcould
bespendinglotoftimetryingtoperformeventhebasicadministrativetasks.Thefocusofthiscourseistohelp
youunderstandsystemadministrationtools,whichwillhelpyoutobecomeaneffectiveLinuxsystem
administrator.
GettheLinuxSysadminCourseNow!

Ifyouenjoyedthisarticle,youmightalsolike..
1. 50LinuxSysadminTutorials
2. 50MostFrequentlyUsedLinuxCommands(With
Examples)
3. Top25BestLinuxPerformanceMonitoringand
DebuggingTools

www.thegeekstuff.com/2013/12/xargs-examples/

AwkIntroduction7AwkPrintExamples
AdvancedSedSubstitutionExamples
8EssentialVimEditorNavigation
Fundamentals
25MostFrequentlyUsedLinuxIPTables

5/11

11/22/14

10 Xargs Command Examples in Linux / UNIX

4. Mommy,Ifoundit!15PracticalLinuxFind
CommandExamples
5. Linux101Hacks2ndEditioneBook

RulesExamples
TurbochargePuTTYwith12PowerfulAdd
Ons

{11commentsreadthembeloworaddone}
1JalalHajigholamaliDecember27,2013at9:36am
Hi,
Veryusefularticle
Thanksalot..
2IrudayarajDecember27,2013at1:29pm
$find.name*.c|xargsgrepstdlib.h
inasimpleform.
$greprstdlib.h*.c
3VladimirLaskovDecember28,2013at4:59am
Pleaseaddthekillerfunctionaflagi
4MustaphaOldacheDecember28,2013at7:06am
HI
Wewantmorelikethis.Thanks.
5SayeedDecember30,2013at4:00am
@Irudayaraj
Ithink,grepshouldhaveoptionltolistthesearchedfiles.
greplrstdlib.h*.c
.
6meowJanuary2,2014at9:44am
theIandJoptionsaretheonesneedtobeintroducedindetail.
7SridharSarnobatJanuary6,2014at5:38pm

www.thegeekstuff.com/2013/12/xargs-examples/

6/11

11/22/14

10 Xargs Command Examples in Linux / UNIX

Theprint0optionforfilenameswithspacesiscumbersomeandcounterintuitiveinmyopinion.Manyyears
afterusingxargsIstartedusingdnandneverhadtothinkaboutspacesagain.Ifonlyxargscouldmakethis
behaviordefault,perhapsthroughashellvariable,itwouldbeevenbetter.
GoodarticleBTW.
8AndyJanuary20,2014at12:08pm
Thxalot..veryhelpful..
9JoeyJuly4,2014at7:25pm
Checkthisout.Inexample2,whenIchangedthesampletexttoincludethelettern,asin:
Hi,
andWelcome
toTGS
andAssociates.
The\ndelimiterstrippedoutallthensinthetext.
Theresultingoutputwas:
Hi,
adWelcome
toTGS
adAssociates.
Putting\ninsingleordoublequotescausedittobeignoredandthetextoutputsonasingleline.
Incaseitwasgnometerminal,IhitCTRLALTF1togetaconsoleandagainthesamebehaviorrepeated.
Hmmm
10SteveBennettAugust26,2014at9:02am
Itsdangeroustousermrfallovertheplacewhenyoudontneedit.Yourepassingindividualfile
namestorm,soyoudontneedtoaddtherecursiveflag.Justusermfandbreatheeasier.
11OleTangeNovember4,2014at6:35am
Using`find`with`xargs`without`print0`canleadtodisaster.Seehere.
LeaveaComment
Name
Email
Website

www.thegeekstuff.com/2013/12/xargs-examples/

7/11

11/22/14

10 Xargs Command Examples in Linux / UNIX

Notifymeoffollowupcommentsviaemail
Submit

Previouspost:HowtoCreateOption,Context,andPopupMenusinAndroidApp
Nextpost:HappyNewYear2014FromGeekandtheDolls
RSS|Email|Twitter|Facebook|Google+
Search

COURSE
LinuxSysadminCentOS6CourseMastertheTools,ConfigureitRight,andbeLazy

EBOOKS
Linux101Hacks2ndEditioneBookPracticalExamplestoBuildaStrongFoundationin
Linux
Bash101HackseBookTakeControlofYourBashCommandLineandShellScripting
SedandAwk101HackseBookEnhanceYourUNIX/LinuxLifewithSedandAwk
Vim101HackseBookPracticalExamplesforBecomingFastandProductiveinVimEditor
NagiosCore3eBookMonitorEverything,BeProactive,andSleepWell

www.thegeekstuff.com/2013/12/xargs-examples/

8/11

11/22/14

10 Xargs Command Examples in Linux / UNIX

POPULARPOSTS
12AmazingandEssentialLinuxBooksToEnrichYourBrainandLibrary
50UNIX/LinuxSysadminTutorials
50MostFrequentlyUsedUNIX/LinuxCommands(WithExamples)
HowToBeProductiveandGetThingsDoneUsingGTD
30ThingsToDoWhenyouareBoredandhaveaComputer
LinuxDirectoryStructure(FileSystemStructure)ExplainedwithExamples
LinuxCrontab:15AwesomeCronJobExamples
GetaGripontheGrep!15PracticalGrepCommandExamples
UnixLSCommand:15PracticalExamples
15ExamplesToMasterLinuxCommandLineHistory
Top10OpenSourceBugTrackingSystem
ViandVimMacroTutorial:HowToRecordandPlay
Mommy,Ifoundit!15PracticalLinuxFindCommandExamples
15AwesomeGmailTipsandTricks
15AwesomeGoogleSearchTipsandTricks
RAID0,RAID1,RAID5,RAID10ExplainedwithDiagrams
CanYouTopThis?15PracticalLinuxTopCommandExamples
Top5BestSystemMonitoringTools
Top5BestLinuxOSDistributions
HowToMonitorRemoteLinuxHostusingNagios3.0
AwkIntroductionTutorial7AwkPrintExamples
HowtoBackupLinux?15rsyncCommandExamples
TheUltimateWgetDownloadGuideWith15AwesomeExamples
Top5BestLinuxTextEditors
PacketAnalyzer:15TCPDUMPCommandExamples
TheUltimateBashArrayTutorialwith15Examples
3StepstoPerformSSHLoginWithoutPasswordUsingsshkeygen&sshcopyid
UnixSedTutorial:AdvancedSedSubstitutionExamples
UNIX/Linux:10NetstatCommandExamples
TheUltimateGuideforCreatingStrongPasswords
6StepstoSecureYourHomeWirelessNetwork
TurbochargePuTTYwith12PowerfulAddOns

CATEGORIES
LinuxTutorials
VimEditor

www.thegeekstuff.com/2013/12/xargs-examples/

9/11

11/22/14

10 Xargs Command Examples in Linux / UNIX

SedScripting
AwkScripting
BashShellScripting
NagiosMonitoring
OpenSSH
IPTablesFirewall
ApacheWebServer
MySQLDatabase
PerlProgramming
GoogleTutorials
UbuntuTutorials
PostgreSQLDB
HelloWorldExamples
CProgramming
C++Programming
DELLServerTutorials
OracleDatabase
VMwareTutorials
Ramesh Natarajan

AboutTheGeekStuff

MynameisRameshNatarajan.Iwillbepostinginstructionguides,howto,
troubleshootingtipsandtricksonLinux,database,hardware,securityandweb.Myfocusistowritearticles
thatwilleitherteachyouorhelpyouresolveaproblem.ReadmoreaboutRameshNatarajanandtheblog.

SupportUs
Supportthisblogbypurchasingoneofmyebooks.
Bash101HackseBook
SedandAwk101HackseBook
Vim101HackseBook
NagiosCore3eBook

ContactUs

www.thegeekstuff.com/2013/12/xargs-examples/

10/11

11/22/14

10 Xargs Command Examples in Linux / UNIX

EmailMe:UsethisContactFormtogetintouchmewithyourcomments,questionsorsuggestionsabout
thissite.Youcanalsosimplydropmealinetosayhello!.
FollowusonGoogle+
FollowusonTwitter
BecomeafanonFacebook
Copyright20082014RameshNatarajan.Allrightsreserved|TermsofService

www.thegeekstuff.com/2013/12/xargs-examples/

11/11

You might also like