How can I call a shell command in my Perl script?
文章推薦指數: 80 %
System will execute the $command with @arguments and return to your script when ... I have been using system and qq to run linux programs inside perl. Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam StackOverflowforTeamsismovingtoitsowndomain!Whenthemigrationiscomplete,youwillaccessyourTeamsatstackoverflowteams.com,andtheywillnolongerappearintheleftsidebaronstackoverflow.com. Checkyouremailforupdates. Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams HowcanIcallashellcommandinmyPerlscript? AskQuestion Asked 12years,3monthsago Modified 11monthsago Viewed 283ktimes 81 New!Savequestionsoranswersandorganizeyourfavoritecontent.Learnmore. WhatwouldbeanexampleofhowIcancallashellcommand,say'ls-a'inaPerlscriptandthewaytoretrievetheoutputofthecommandaswell? perl Share Follow editedApr20,2019at1:40 PeterMortensen 30.6k2121goldbadges102102silverbadges124124bronzebadges askedJul8,2010at5:07 YangYang 9,6941515goldbadges4343silverbadges5252bronzebadges Addacomment | 8Answers 8 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 97 HowtorunashellscriptfromaPerlprogram 1.Usingsystemsystem($command,@arguments); Forexample: system("sh","script.sh","--help"); system("shscript.sh--help"); Systemwillexecutethe$commandwith @argumentsandreturntoyourscriptwhenfinished.Youmaycheck$! forcertainerrorspassedtotheOSbytheexternalapplication.Read thedocumentationforsystemforthenuancesofhowvarious invocationsareslightlydifferent. 2.Usingexec Thisisverysimilartotheuseofsystem,butitwill terminateyourscriptuponexecution.Again,readthedocumentation forexecformore. 3.Usingbackticksorqx// my$output=`script.sh--option`; my$output=qx/script.sh--option/; Thebacktickoperatorandit'sequivalentqx//,excutethecommandandoptionsinsidetheoperatorandreturnthatcommandsoutputtoSTDOUTwhenitfinishes. Therearealsowaystorunexternalapplicationsthroughcreativeuseofopen,butthisisadvanceduse;readthedocumentationformore. Share Follow editedApr30,2020at15:37 PabloBianchi 1,53811goldbadge2222silverbadges3030bronzebadges answeredJul8,2010at5:11 fire.eaglefire.eagle 2,6532121silverbadges2323bronzebadges 4 1 system()givesuoutputinruntime. – ANjaNA Jun24,2016at8:08 1 Idon'tthinktilda`workswithlatestperl(5.24.0) – PMat May30,2017at19:53 5 Thatiscalledabacktick`...forprogramminganyway,whenusedinforeignlanguagesitisanaccent.Atilde(noticethe"e"attheend,ratherthan"a")isthesquigglyline;whichinPerlisusedforpatternmatchingandsmartmatching. – Tyler Jan4,2018at16:20 fortheqx/orbacktickoneadd2>&1tocapturealsostderr. – yerlilbilgin May12,2018at23:21 Addacomment | 27 FromPerlHowTo,themostcommonwaystoexecuteexternalcommandsfromPerlare: my$files=`ls-la`—capturestheoutputofthecommandin$files system"touch~/foo"—ifyoudon'twanttocapturethecommand'soutput exec"vim~/foo"—ifyoudon'twanttoreturntothescriptafterexecutingthecommand open(my$file,'|-',"grepfoo");print$file"foo\nbar"—ifyouwanttopipeinputintothecommand Share Follow editedJan16,2014at6:26 answeredJan16,2014at3:52 sjysjy 2,67211goldbadge2020silverbadges2222bronzebadges Addacomment | 15 Examples `ls-l`; system("ls-l"); exec("ls-l"); Share Follow editedJun20,2020at9:12 CommunityBot 111silverbadge answeredJul8,2010at6:45 user376314user376314 2 7 Youshouldexplainwhatarethedifferencesbetweenthesemethods.Also,IbelievenotallofthemsolvetheproblemthatOPhas(callingexecdoesnotreturntotheperlscriptAFAIR) – K.L. May15,2014at9:45 1 @K.L.Youarecorrect,withoutsomenastyhacksexecwillexittheperlscriptwiththesameexitcodeasthepassedcommand. – scragar Aug18,2014at15:19 Addacomment | 12 LookattheopenfunctioninPerl-especiallythevariantsusinga'|'(pipe)inthearguments.Donecorrectly,you'llgetafilehandlethatyoucanusetoreadtheoutputofthecommand.Thebacktickoperatorsalsodothis. YoumightalsowanttoreviewwhetherPerlhasaccesstotheCfunctionsthatthecommanditselfuses.Forexample,forls-a,youcouldusetheopendirfunction,andthenreadthefilenameswiththereaddirfunction,andfinallyclosethedirectorywith(surprise)theclosedirfunction.Thishasanumberofbenefits-precisionprobablybeingmoreimportantthanspeed.Usingthesefunctions,youcangetthecorrectdataevenifthefilenamescontainoddcharacterslikenewline. Share Follow answeredJul8,2010at5:27 JonathanLefflerJonathanLeffler 709k135135goldbadges878878silverbadges12391239bronzebadges Addacomment | 10 AsyoubecomemoreexperiencedwithusingPerl,you'llfindthattherearefewerandfeweroccasionswhenyouneedtorunshellcommands.Forexample,onewaytogetalistoffilesistousePerl'sbuilt-inglobfunction.Ifyouwantthelistinsortedorderyoucouldcombineitwiththebuilt-insortfunction.Ifyouwantdetailsabouteachfile,youcanusethestatfunction.Here'sanexample: #!/usr/bin/perl usestrict; usewarnings; foreachmy$file(sortglob('/home/grant/*')){ my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) =stat($file); printf("%-40s%8ubytes\n",$file,$size); } Share Follow answeredJul9,2010at21:28 GrantMcLeanGrantMcLean 6,79811goldbadge2020silverbadges3636bronzebadges 1 Obviouslythisanswerdoesn'tapplytocommandsotherthanls,butinthecasethattheuserwasactuallygoingtocallls,thisanswerdeservesrecognitionforansweringtheuser'sintentionratherthantheiractualquestion. – M_M May1,2020at9:10 Addacomment | 6 TherearealotofwaysyoucancallashellcommandfromaPerlscript,suchas: backtick lswhichcapturestheoutputandgivesbacktoyou. system system('ls'); open Refer#17here:Perlprogrammingtips Share Follow editedNov23,2019at16:09 PeterMortensen 30.6k2121goldbadges102102silverbadges124124bronzebadges answeredJul8,2010at5:57 thegeekthegeek 2,30822goldbadges1313silverbadges1010bronzebadges Addacomment | 1 Youmightwanttolookintoopen2andopen3incaseyouneedbidirectionalcommunication. Share Follow answeredJul8,2010at14:59 miedwarmiedwar 7,21011goldbadge1515silverbadges1515bronzebadges Addacomment | 1 Ihavebeenusingsystemandqqtorunlinuxprogramsinsideperl.Andithasworkedwell. #!/usr/bin/perl#Ahashbanglineinperl usestrict;#Itcansaveyoualotoftimeandheadache usewarnings;#Ithelpsyoufindtypingmistakes #mykeywordinPerldeclaresthelistedvariable my$adduser='/usr/sbin/adduser'; my$edquota='/usr/sbin/edquota'; my$chage='/usr/bin/chage'; my$quota='/usr/bin/quota'; my$nomeinteiro; my$username; my$home; #system()functionexecutesasystemshellcommand #qq()canbeusedinplaceofdoublequotes systemqq($adduser--home$home--gecos"$fullname"$username); systemqq($edquota-pjohn$username); systemqq($chage-E\$(date-d+180days+%Y-%m-%d)$username); systemqq($chage-l$username); systemqq($quota-s$username); Share Follow editedNov12,2021at20:08 answeredNov9,2021at21:28 UlissesUlisses 3144bronzebadges 2 Theanswerwouldbemoreusefulifyoucanaddsomeexplanationalongwiththecode. – holydragon Nov11,2021at10:35 Thanksforthereview.nowIputmorecommentstogetabetterunderstanding. – Ulisses Nov12,2021at20:10 Addacomment | YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedperloraskyourownquestion. TheOverflowBlog IntroducingtheOverflowOfflineproject Hehelpedbuild.NETandVSCode—Now’sheworkingonWeb3(Ep.499) FeaturedonMeta The2022Community-a-thonhasbegun! Mobileappinfrastructurebeingdecommissioned Visitchat Linked 0 Invokeperlscriptfromanotherperlscript 7 Callabashscriptfromaperlscript 1 bashcommandinPerlscript-passoutput
延伸文章資訊
- 17 of the most useful Perl command line options
7 of the most useful Perl command line options · -v to get the Perl version · -V to get compiler ...
- 2Perl Command-Line Options
Perl has a large number of command-line options that can help to make your programs more concise ...
- 3perl linux command man page
Perl officially stands for Practical Extraction and Report Language, except when it doesn't. ... ...
- 4Linux perl command help and examples - Computer Hope
The perl command is the interpreter of the Perl programming language. Description. "Perl" officia...
- 5How to Run Perl Scripts in Linux Command Line
Learn to learn Perl scripts in Linux command line. Also learn a few tricks about running Perl com...