Beruflich Dokumente
Kultur Dokumente
TheUnixandGNU/Linuxcommandline
MichaelOpdenacker FreeElectrons http://freeelectrons.com
CreatedwithOpenOffice.org2.0
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
Rightstocopy
Copyright20042007 FreeElectrons feedback@freeelectrons.com Documentsources,updatesandtranslations:
http://freeelectrons.com/training/intro_unix_linux
AttributionShareAlike2.5 Youarefree tocopy,distribute,display,andperformthework tomakederivativeworks tomakecommercialuseofthework Underthefollowingconditions Attribution.Youmustgivetheoriginalauthorcredit. ShareAlike.Ifyoualter,transform,orbuilduponthiswork, youmaydistributetheresultingworkonlyunderalicense identicaltothisone. Foranyreuseordistribution,youmustmakecleartoothersthe licensetermsofthiswork. Anyoftheseconditionscanbewaivedifyougetpermissionfrom thecopyrightholder. Yourfairuseandotherrightsareinnowayaffectedbytheabove. Licensetext:http://creativecommons.org/licenses/bysa/2.5/legalcode
Corrections,suggestions,contributionsand translationsarewelcome!
Bestviewedwith...
ThisdocumentisbestviewedwitharecentPDFreader orwithOpenOffice.orgitself! Takeadvantageofinternalorexternalhyperlinks. So,donthesitatetoclickonthem! Findpagesquicklythankstoautomaticsearch Usethumbnailstonavigateinthedocumentinaquickway IfyourereadingapaperorHTMLcopy,youshouldgetyour copyinPDForOpenOffice.orgformaton http://freeelectrons.com/training/intro_unix_linux!
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
Commandmementosheet
Itisausefulcompaniontothis presentation. Examplesforthemostuseful commandsaregiveninjustonesheet. Suggestionsforuse Stickthissheetonyourwall,useitas desktopwallpaper,makeitamouse mat,printitonclothing,sliceitinto bookmarks...
Getiton http://freeelectrons.com/training/intro_unix_linux
Caution Storeawayfrommice!
TrainingContents(1)
Shells,filesystemandfilehandling Everythingisafile GNU/Linuxfilesystemstructure Commandlineinterpreters Handlingfilesanddirectories Displaying,scanningandsortingfiles Symbolicandhardlink Fileaccessrights
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
Trainingcontents(2)
StandardI/O,redirections,pipes Standardinputandoutput,redirectingtofiles Pipes:redirectingstandardoutputtoothercommands Standarderror
TrainingContents(3)
Taskcontrol Fullcontrolontasks Executinginbackground,suspending,resumingandaborting Listofactivetasks Killingprocesses Environmentvariables PATHenvironmentvariables Shellaliases,.bashrcfile
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
Trainingcontents(4)
Miscellaneous
Trainingcontents(5)
Systemadministrationbasics Fileownership Settingupnetworking Filesystems:creatingandmounting Goingfurther Gettinghelp,accessingmanualpages SearchingtheInternetforresources
GNU/LinuxandFreeSoftware
ThispresentationincludedanintroductiontoFreeSoftware andOpenSource:operatingsystems,applications,key projectsandrulesforsuccess. Itisnowavailableasaseparatepresentation: http://freeelectrons.com/articles/freesw
10
TheUnixandGNU/Linuxcommandline
Unixfilesystem
11
Everythingisafile
AlmosteverythinginUnixisafile! Regularfiles Directories Directoriesarejustfiles listingasetoffiles Symboliclinks Filesreferringtothenameof anotherfile Devicesandperipherals Readandwritefromdevicesas withregularfiles Pipes Usedtocascadeprograms cat*.log|greperror Sockets Interprocesscommunication
12
Filenames
FilenamefeaturessincethebeginningofUnix Casesensitive Noobviouslengthlimit Cancontainanycharacter(includingwhitespace,except/). Filetypesstoredinthefile(magicnumbers). Filenameextensionsnotneededandnotinterpreted.Justusedfor userconvenience. Filenameexamples: README .bashrc index.htm index.html WindowsBuglist index.html.old
13
Filepaths
Apathisasequenceofnesteddirectorieswithafileordirectoryat theend,separatedbythe/character Relativepath:documents/fun/microsoft_jokes.html Relativetothecurrentdirectory Absolutepath:/home/bill/bugs/crash9402031614568 /:rootdirectory. Startofabsolutepathsforallfilesonthesystem(evenforfileson removabledevicesornetworkshared).
14
GNU/Linuxfilesystemstructure(1)
Notimposedbythesystem.Canvaryfromonesystemtotheother, evenbetweentwoGNU/Linuxinstallations! / /bin/ /boot/ /dev/ /etc/ /home/ /lib/ Rootdirectory Basic,essentialsystemcommands Kernelimages,initrdandconfigurationfiles Filesrepresentingdevices /dev/hda:firstIDEharddisk Systemconfigurationfiles Userdirectories Basicsystemsharedlibraries
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
15
GNU/Linuxfilesystemstructure(2)
/lost+found /media /mnt/ /opt/ /proc/ /root/ /sbin/ /sys/ Corruptfilesthesystemtriedtorecover Mountpointsforremovablemedia: /media/usbdisk,/media/cdrom Mountpointsfortemporarilymountedfilesystems Specifictoolsinstalledbythesysadmin /usr/local/oftenusedinstead Accesstosysteminformation /proc/cpuinfo,/proc/version... rootuserhomedirectory Administratoronlycommands Systemanddevicecontrols (cpufrequency,devicepower,etc.)
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
16
GNU/Linuxfilesystemstructure(3)
/tmp/ /usr/ /usr/local/ /var/ Temporaryfiles Regularusertools(notessentialtothesystem) /usr/bin/,/usr/lib/,/usr/sbin... Specificsoftwareinstalledbythesysadmin (oftenpreferredto/opt/) Datausedbythesystemorsystemservers /var/log/,/var/spool/mail(incoming mail),/var/spool/lpd(printjobs)...
17
TheUnixandGNU/Linuxcommandline
Shellsandfilehandling
18
Commandlineinterpreters
Shells:toolstoexecuteusercommands Calledshellsbecausetheyhidethedetailsonthe underlyingoperatingsystemundertheshell'ssurface. Commandsareinputinatextterminal,eitherawindowina graphicalenvironmentoratextonlyconsole. Resultsarealsodisplayedontheterminal.Nographicsare neededatall. Shellscanbescripted:providealltheresourcestowrite complexprograms(variable,conditionals,iterations...)
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
19
Wellknownshells
Mostfamousandpopularshells sh:TheBourneshell(obsolete) Traditional,basicshellfoundonUnixsystems,bySteveBourne. csh:TheCshell(obsolete) OncepopularshellwithaClikesyntax tcsh:TheTCshell(stillverypopular) ACshellcompatibleimplementationwithevolvedfeatures(command completion,historyeditingandmore...) bash:TheBourneAgainshell(mostpopular) Animprovedimplementationofshwithlotsofaddedfeaturestoo.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
20
fish:agreatnewshell
TheFriendlyInteractiveSHell http://www.fishshell.org/ Standardfeatures:history,commandandfilecompletion... Brandnewfeatures:commandoptioncompletion,command completionwithshortdescription,syntaxhighlighting.. Easiertoanyopenfiles:openbuiltincommand. Muchsimplerandconsistentsyntax(notPOSIXcompliant) Makesiteasiertocreateshellscripts. Commandlinebeginnerscanlearnmuchfaster! Evenexperiencedusersshouldfindthisshellveryconvenient.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
21
lscommand
Liststhefilesinthecurrentdirectory,inalphanumericorder, exceptfilesstartingwiththe.character. lsa(all) Listsallthefiles(including.* files) lsl(long) Longlisting(type,date,size, owner,permissions) lst(time) Liststhemostrecentfilesfirst lsS(size) Liststhebiggestfilesfirst lsr(reverse) Reversesthesortorder lsltr(optionscanbe combined) Longlisting,mostrecentfilesat theend
22
Filenamepatternsubstitutions
Betterintroducedbyexamples! ls*txt Theshellfirstreplaces*txtbyallthefileanddirectorynames endingbytxt(including.txt),exceptthosestartingwith., andthenexecutesthelscommandline. lsd.* Listsallthefilesanddirectoriesstartingwith. dtellslsnottodisplaythecontentsofdirectories. cat?.log Displaysallthefileswhichnamesstartby1characterandend by.log
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
23
Specialdirectories(1)
./ Thecurrentdirectory.Usefulforcommandstakingadirectory argument.Alsosometimesusefultoruncommandsinthecurrent directory(seelater). So./readme.txtandreadme.txtareequivalent. ../ Theparent(enclosing)directory.Alwaysbelongstothe.directory (seelsa).Onlyreferencetotheparentdirectory. Typicalusage: cd..
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
24
Specialdirectories(2)
~/ Notaspecialdirectoryindeed.Shellsjustsubstituteitbythe homedirectoryofthecurrentuser. Cannotbeusedinmostprograms,asitisnotarealdirectory. ~sydney/ Similarly,substitutedbyshellsbythehomedirectoryofthe sydneyuser.
25
Thecdandpwdcommands
cd<dir> Changesthecurrentdirectoryto<dir>. cd Getsbacktothepreviouscurrentdirectory. pwd Displaysthecurrentdirectory("workingdirectory").
26
Thecpcommand
cp<source_file><target_file> Copiesthesourcefiletothetarget. cpfile1file2file3...dir Copiesthefilestothetargetdirectory(lastargument). cpi(interactive) Asksforuserconfirmationifthetargetfilealreadyexists cpr<source_dir><target_dir>(recursive) Copiesthewholedirectory.
27
Smartdirectorycopywithrsync
rsync(remotesync)hasbeendesignedtokeepinsync directorieson2machineswithalowbandwidthconnection.
Onlycopiesfilesthathavechanged.Fileswiththesamesizearecompared bychecksums. Onlytransferstheblocksthatdifferwithinafile! Cancompressthetransferredblocks Preservessymboliclinksandfilepermissions:alsoveryusefulforcopieson thesamemachine. Canworkthroughssh(secureremoteshell).Veryusefultoupdatethe contentsofawebsite,forexample.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
28
rsyncexamples(1)
rsynca/home/arvin/sd6_agents//home/sydney/misc/
a:archivemode.EquivalenttorlptgoD...easywaytotellyouwant recursionandwanttopreservealmosteverything.
rsyncPavdelete/home/steve/ideas//home/bill/my_ideas/
29
rsyncexamples(2)
Copyingtoaremotemachine rsyncPav/home/bill/legal/arguments/\ bill@www.sco.com:/home/legal/arguments/ Userbillwillbepromptedforapassword. Copyingfromaremotemachinethroughssh rsyncPavessh homer@tank.duff.com:/prod/beer/\ fridge/homer/beer/ Userhomerwillbepromptedforhissshkeypassword.
30
mvandrmcommands
mv<old_name><new_name> (move) Renamesthegivenfileordirectory. mvi(interactive) Ifthenewfilealreadyexits,asksforuserconfirm rmfile1file2file3... (remove) Removesthegivenfiles. rmi(interactive) Alwaysaskforuserconfirm. rmrdir1dir2dir3(recursive) Removesthegivendirectorieswithalltheircontents.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
31
Creatingandremovingdirectories
mkdirdir1dir2dir3...(makedir) Createsdirectorieswiththegivennames. rmdirdir1dir2dir3...(removedir) Removesthegivendirectories Safe:onlyworkswhendirectoriesandempty. Alternative:rmr(doesn'tneedemptydirectories).
32
Displayingfilecontents
Severalwaysofdisplayingthecontentsoffiles. catfile1file2file3...(concatenate) Concatenatesandoutputsthecontentsofthegivenfiles. morefile1file2file3... Aftereachpage,askstheusertohitakeytocontinue. Canalsojumptothefirstoccurrenceofakeyword (/command). lessfile1file2file3... Doesmorethanmorewithless. Doesn'treadthewholefilebeforestarting. Supportsbackwardmovementinthefile(?command).
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
33
Theheadandtailcommands
head[<n>]<file> Displaysthefirst<n>lines(or10bydefault)ofthegivenfile. Doesn'thavetoopenthewholefiletodothis! tail[<n>]<file> Displaysthelast<n>lines(or10bydefault)ofthegivenfile. NoneedtoloadthewholefileinRAM!Veryusefulforhugefiles. tailf<file>(follow) Displaysthelast10linesofthegivenfileandcontinuestodisplaynewlines whentheyareappendedtothefile. Veryusefultofollowthechangesinalogfile,forexample. Examples headwindows_bugs.txt tailfoutlook_vulnerabilities.txt
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
34
Thegrepcommand
grep<pattern><files> Scansthegivenfilesanddisplaysthelineswhichmatchthegivenpattern. greperror*.log Displaysallthelinescontainingerrorinthe*.logfiles grepierror*.log Same,butcaseinsensitive greprierror. Same,butrecursivelyinallthefilesin.anditssubdirectories grepvinfo*.log Outputsallthelinesinthefilesexceptthosecontaininginfo.
35
Thesortcommand
sort<file> Sortsthelinesinthegivenfileincharacterorderand outputsthem. sortr<file> Same,butinreverseorder. sortru<file> u:unique.Same,butjustoutputsidenticallinesonce. Morepossibilitiesdescribedlater!
36
Symboliclinks
Asymboliclinkisaspecialfilewhichisjustareferencetothe nameofanotherone(fileordirectory): Usefultoreducediskusageandcomplexitywhen2fileshavethe samecontent. Example:
anakin_skywalker_biography>darth_vador_biography
Howtoidentifysymboliclinks:
lsldisplays>andthelinkedfilename. GNUlsdisplayslinkswithadifferentcolor.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
37
Creatingsymboliclinks
Tocreateasymboliclink(sameorderasincp): lnsfile_namelink_name Tocreatealinkwithtoafileinanotherdirectory,withthe samename: lns../README.txt Tocreatemultiplelinksatonceinagivendirectory: lnsfile1file2file3...dir Toremovealink: rmlink_name Ofcourse,thisdoesn'tremovethelinkedfile!
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
38
Hardlinks
Thedefaultbehaviorforlnistocreatehardlinks Ahardlinktoafileisaregularfilewithexactlythesame physicalcontents Whiletheystillsavespace,hardlinkscan'tbedistinguished fromtheoriginalfiles. Ifyouremovetheoriginalfile,thereisnoimpactonthehard linkcontents. Thecontentsareremovedwhentherearenomorefiles(hard links)tothem.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
39
Filesnamesandinodes
Makeshardandsymbolic(soft)linkseasiertounderstand!
Users Filenameinterface
Softlink
rm
File Inode
Hardlink
rm
40
Fileaccessrights
Uselsltocheckfileaccessrights
3typesofaccessrights Readaccess(r) Writeaccess(w) Executerights(x) 3typesofaccesslevels User(u):fortheownerofthe file Group(g):eachfilealsohasa groupattribute,corresponding toagivenlistofusers Others(o):forallotherusers
41
Accessrightconstraints
xwithoutrislegalbutisuseless Youhavetobeabletoreadafiletoexecuteit. Bothrandxpermissionsneededfordirectories: xtoenter,rtolistitscontents. Youcan'trename,remove,copyfilesinadirectoryifyoudon't havewaccesstothisdirectory. Ifyouhavewaccesstoadirectory,youCANremoveafileevenif youdon'thavewriteaccesstothisfile(rememberthatadirectory isjustafiledescribingalistoffiles).Thisevenletsyoumodify (remove+recreate)afileevenwithoutwaccesstoit.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
42
Accessrightsexamples
rwrr Readableandwritableforfileowner,onlyreadableforothers rwr Readableandwritableforfileowner,onlyreadableforusers belongingtothefilegroup. drwx Directoryonlyaccessiblebyitsowner rx Fileexecutablebyothersbutneitherbyyourfriendsnorby yourself.Niceprotectionsforatrap...
43
chmod:changingpermissions
chmod<permissions><files> 2formatsforpermissions: Octalformat(abc): a,b,c=r*4+w*2+x(r,w,x:booleans) Example:chmod644<file> (rwforu,rforgando) Orsymbolicformat.Easytounderstandbyexamples: chmodgo+r:addreadpermissionstogroupandothers. chmoduw:removewritepermissionsfromuser. chmodax:(a:all)removeexecutepermissionfromall.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
44
Morechmod(1)
chmodRa+rXlinux/ Makeslinuxandeverythinginitavailableto everyone! R:applychangesrecursively X:x,butonlyfordirectoriesandfilesalreadyexecutable Veryusefultoopenrecursiveaccesstodirectories, withoutaddingexecutionrightstoallfiles.
45
Morechmod(2)
chmoda+t/tmp t:(sticky).Specialpermissionfordirectories,allowing onlythedirectoryandfileownertodeleteafileina directory. Usefulfordirectorieswithwriteaccesstoanyone, like/tmp. Displayedbylslwithatcharacter.
46
TheUnixandGNU/Linuxcommandline
StandardI/O,redirections,pipes
47
Standardoutput
Moreaboutcommandoutput Allthecommandsoutputtingtextonyourterminaldoitby writingtotheirstandardoutput. Standardoutputcanbewritten(redirected)toafileusingthe >symbol Standardoutputcanbeappendedtoanexistingfileusingthe >>symbol
48
Standardoutputredirectionexamples
ls~saddam/*>~gwb/weapons_mass_destruction.txt catobiwan_kenobi.txt>starwars_biographies.txt cathan_solo.txt>>starwars_biographies.txt echoREADME:Nosuchfileordirectory>README Usefulwayofcreatingafilewithoutatexteditor. NiceUnixjoketoointhiscase.
49
Standardinput
Moreaboutcommandinput Lotsofcommands,whennotgiveninputarguments,cantaketheir inputfromstandardinput. sort windows linux [Ctrl][D] linux windows sorttakesitsinputfrom thestandardinput:inthiscase, whatyoutypeintheterminal (endedby[Ctrl][D])
sort<participants.txt Thestandardinputofsortistakenfromthegivenfile.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
50
Pipes
Unixpipesareveryusefultoredirectthestandardoutputofa commandtothestandardinputofanotherone. Examples
cat*.log|grepierror|sort greprierror.|grepvignored|sortu\ >serious_errors.log cat/home/*/homework.txt|grepmark|more
ThisoneofthemostpowerfulfeaturesinUnixshells!
51
Theteecommand
tee[a]file Theteecommandcanbeusedtosendstandardoutput tothescreenandtoafilesimultaneously. make|teebuild.log Runsthemakecommandandstoresitsoutputto build.log. makeinstall|teeabuild.log Runsthemakeinstallcommandandappendsits outputtobuild.log.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
52
Standarderror
Errormessagesareusuallyoutput(iftheprogramiswellwritten) tostandarderrorinsteadofstandardoutput. Standarderrorcanberedirectedthrough2>or2>> Example: catf1f2nofile>newfile2>errfile Note:1isthedescriptorforstandardoutput,so1>isequivalent to>. Canredirectbothstandardoutputandstandarderrortothesame fileusing&>: catf1f2nofile&>wholefile
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
53
Theyescommand
Usefultofillstandardinputwithalwaysthesamestring. yes<string>|<command> Keepsfillingthestandardinputof<command>with <string>(ybydefault). Examples yes|rmrdir/ bank>yesno|credit_applicant yes""|makeoldconfig (equivalenttohitting[Enter]toacceptalldefaultsettings)
54
Specialdevices(1)
Devicefileswithaspecialbehaviororcontents /dev/null Thedatasink!Discardsalldatawrittentothisfile. Usefultogetridofunwantedoutput,typicallyloginformation: mplayerblack_adder_4th.avi&>/dev/null /dev/zero Readsfromthisfilealwaysreturn\0characters Usefultocreateafilefilledwithzeros: ddif=/dev/zeroof=disk.imgbs=1kcount=2048
Seemannullormanzerofordetails
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
55
Specialdevices(2)
/dev/random Returnsrandombyteswhenread.Mainlyusedbycryptographic programs.Usesinterruptsfromsomedevicedriversassourcesof truerandomness(entropy). Readscanbeblockeduntilenoughentropyisgathered. /dev/urandom Forprogramsforwhichpseudorandomnumbersarefine. Alwaysgeneratesrandombytes,evenifnotenoughentropyis available(inwhichcaseitispossible,thoughstilldifficult,to predictfuturebytesequencesfrompastones). Seemanrandomfordetails.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
56
Specialdevices(3)
/dev/full Mimicsafulldevice. Usefultocheckthatyourapplicationproperlyhandles thiskindofsituation. Seemanfullfordetails.
57
TheUnixandGNU/Linuxcommandline
Taskcontrol
58
Fullcontrolontasks
Sincethebeginning,Unixsupportstruepreemptive multitasking. Abilitytorunmanytasksinparallel,andabortthemevenif theycorrupttheirownstateanddata. Abilitytochoosewhichprogramsyourun. Abilitytochoosewhichinputyourprogramstakes,and wheretheiroutputgoes.
59
Processes
EverythinginUnixisafile EverythinginUnixthatisnotafileisaprocess Processes Instancesofarunningprograms Severalinstancesofthesameprogramcanrunatthesametime Dataassociatedtoprocesses: Openfiles,allocatedmemory,stack,processid,parent,priority,state...
60
Runningjobsinbackground
Sameusagethroughoutalltheshells Useful
Forcommandlinejobswhichoutputcanbeexaminedlater, especiallyfortimeconsumingones. Tostartgraphicalapplicationsfromthecommandlineand thencontinuewiththemouse.
Startingatask:add&attheendofyourline:
find_prince_charmingcutecleverrich&
61
Backgroundjobcontrol
jobs Returnsthelistofbackgroundjobsfromthesameshell
[1]Running~/bin/find_meaning_of_lifewithoutgod& [2]+Runningmakemistakes&
62
Jobcontrolexample
>jobs [1]Running~/bin/find_meaning_of_lifewithoutgod& [2]+Runningmakemistakes& >fg makemistakes >[Ctrl]Z [2]+Stoppedmakemistakes >bg [2]+makemistakes& >kill%1 [1]+Terminated~/bin/find_meaning_of_lifewithoutgod
63
Listingallprocesses
...whatevershell,scriptorprocesstheyarestartedfrom psux Listsalltheprocessesbelongingtothecurrentuser psaux(Note:psedfonSystemVsystems) Listsalltheprocessesrunningonthesystem
psaux|grepbart|grepbash USERPID%CPU%MEMVSZRSSTTYSTATSTARTTIMECOMMAND bart30390.00.259161380pts/2S14:350:00/bin/bash bart31340.00.253881380pts/3S14:360:00/bin/bash bart31900.00.263681360pts/4S14:370:00/bin/bash bart34160.00.000pts/2RW15:070:00[bash] PID: VSZ: RSS: TTY: STAT: Processid Virtualprocesssize(code+data+stack) Processresidentsize:numberofKBcurrentlyinRAM Terminal Status:R(Runnable),S(Sleep),W(paging),Z(Zombie)...
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
64
Liveprocessactivity
topDisplaysmostimportantprocesses,sortedbycpupercentage
top15:44:33up1:11,5users,loadaverage:0.98,0.61,0.59 Tasks:81total,5running,76sleeping,0stopped,0zombie Cpu(s):92.7%us,5.3%sy,0.0%ni,0.0%id,1.7%wa,0.3%hi,0.0%si Mem:515344ktotal,512384kused,2960kfree,20464kbuffers Swap:1044184ktotal,0kused,1044184kfree,277660kcached PIDUSERPRNIVIRTRESSHRS%CPU%MEMTIME+COMMAND 3809jdoe250625639321312R93.80.80:21.49bunzip2 2769root160157m80m90mR2.716.05:21.01X 3006jdoe1503092815m27mS0.33.00:22.40kdeinit 3008jdoe16056248924468S0.30.20:06.59autorun 3034jdoe1502676412m24mS0.32.50:12.68kscd 3810jdoe16028929161620R0.30.20:00.06top
65
Killingprocesses(1)
kill<pids> Sendsanabortsignaltothegivenprocesses.Letsprocessessave dataandexitbythemselves.Shouldbeusedfirst.Example: kill3039313431903416 kill9<pids> Sendsanimmediateterminationsignal.Thesystemitself terminatestheprocesses.Usefulwhenaprocessisreallystuck (doesn'tanswertokill1). kill91 Killsalltheprocessesofthecurrentuser.1:meansallprocesses.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
66
Killingprocesses(2)
killall[<signal>]<command> Killsallthejobsrunning<command>.Example: killallbash xkill Letsyoukillagraphicalapplicationbyclickingonit! Veryquick!Convenientwhenyoudon'tknowtheapplication commandname.
67
Recoveringfromstuckgraphics
Ifyourgraphicalsessionisstuckandyoucannolongertypeinyour terminals,don'treboot! Itisverylikelythatyoursystemisstillfine.Trytoaccessatextconsoleby pressingthe[Ctrl][Alt][F1]keys (or[F2],[F3]formoretextconsoles) Inthetextconsole,youcantrytokilltheguiltyapplication. Oncethisisdone,youcangobacktothegraphicsessionbypressing [Ctrl][Alt][F5]or[Ctrl][Alt][F7](dependingonyour distribution) Ifyoucan'tidentifythestuckprogram,youcanalsokillallyourprocesses: kill91 Youarethenbroughtbacktotheloginscreen.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
68
Sequentialcommands
Cantypethenextcommandinyourterminalevenwhenthe currentoneisnotover. Canseparatecommandswiththe;symbol: echoIlovethee;sleep10;echonot Conditionals:use||(or)or&&(and): moreGod||echoSorry,Goddoesn'texist Runsechoonlyifthefirstcommandfails ls~sd6&&cat~sd6/*>~sydney/recipes.txt Onlycatsthedirectorycontentsifthelscommandsucceeds (meansreadaccess).
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
69
Quoting(1)
Double(")quotescanbeusedtopreventtheshellfrominterpreting spacesasargumentseparators,aswellastopreventfilenamepattern expansion. >echo"HelloWorld" HelloWorld >echo"Youareloggedas$USER" Youareloggedasbgates >echo*.log find_prince_charming.logcosmetic_buys.log >echo"*.log" *.log
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
70
Quoting(2)
Singlequotesbringasimilarfunctionality,butwhatisbetween quotesisneversubstituted >echo'Youareloggedas$USER' Youareloggedas$USER Backquotes(`)canbeusedtocallacommandwithinanother >cd/lib/modules/`unamer`;pwd /lib/modules/2.6.91.6_FC2 Backquotescanbeusedwithindoublequotes >echo"YouareusingLinux`unamer`" YouareusingLinux2.6.91.6_FC2
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
71
Measuringelapsedtime
timefind_expensive_housingnear <...commandoutput...> real0m2.304s(actualelapsedtime) user0m0.449s(CPUtimerunningprogramcode) sys0m0.106s(CPUtimerunningsystemcalls) real=user+sys+waiting waiting=I/Owaitingtime+idletime(runningothertasks)
72
Environmentvariables
Shellslettheuserdefinevariables. Theycanbereusedinshellcommands. Convention:lowercasenames Youcanalsodefineenvironmentvariables:variables thatarealsovisiblewithinscriptsorexecutablescalled fromtheshell. Convention:uppercasenames. env Listsalldefinedenvironmentvariablesandtheirvalue.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
73
Shellvariablesexamples
Shellvariables(bash) projdir=/home/marshall/coolstuff lsla$projdir;cd$projdir Environmentvariables(bash) cd$HOME exportDEBUG=1 ./find_extraterrestrial_life (displaysdebuginformationifDEBUGisset)
74
Mainstandardenvironmentvariables
Usedbylotsofapplications!
LD_LIBRARY_PATH MANPATH
Manualpagesearchpath
PATH
Sharedlibrarysearchpath
DISPLAY
Commandsearchpath
PRINTER
ScreenidtodisplayX (graphical)applicationson.
EDITOR
Defaultprintername
SHELL
Defaulteditor(vi,emacs...)
HOME
Currentshellname
TERM
Currentuserhomedirectory
HOSTNAME
Currentterminaltype
USER
Nameofthelocalmachine
Currentusername
75
PATHenvironmentvariables
PATH Specifiestheshellsearchorderforcommands / home/acox/bin:/usr/local/bin:/usr/kerberos/bin: /usr/bin:/bin:/usr/X11R6/bin:/bin:/usr/bin LD_LIBRARY_PATH Specifiesthesharedlibrary(binarycodelibrariessharedby applications,liketheClibrary)searchorderforld /usr/local/lib:/usr/lib:/lib:/usr/X11R6/lib MANPATH Specifiesthesearchorderformanualpages /usr/local/man:/usr/share/man
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
76
PATHusagewarning
Itisstronglyrecommendednottohavethe.directoryinyourPATH environmentvariable,inparticularnotatthebeginning: Acrackercouldplaceamaliciouslsfileinyourdirectories.Itwould getexecutedwhenyourunlsinthisdirectoryandcoulddonaughty thingstoyourdata. Ifyouhaveanexecutablefilecalledtestinadirectory,thiswill overridethedefaulttestprogramandsomescriptswillstopworking properly. Eachtimeyoucdtoanewdirectory,theshellwillwastetimeupdating itslistofavailablecommands. Callyourlocalcommandsasfollows:./test
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
77
Alias
Shellsletyoudefinecommandaliases:shortcutsforcommandsyouuse veryfrequently. Examples
aliasls='lsla' Usefultoalwaysruncommandswithdefaultarguments. aliasrm='rmi' Usefultomakermalwaysaskforconfirmation. aliasfrd='find_rambaldi_deviceasaprisky' Usefultoreplaceverylongandfrequentcommands. aliascia='./home/sydney/env/cia.sh' Usefultosetanenvironmentinaquickway (.isashellcommandtoexecutethecontentofashellscript).
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
78
Thewhichcommand
Beforeyourunacommand,whichtellsyouwhereitisfound bash>whichls aliasls='lscolor=tty' /bin/ls tcsh>whichls ls:aliasedtolscolor=tty bash>whichalias /usr/bin/which:noaliasin (/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin) tcsh>whichalias alias:shellbuiltincommand.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
79
~/.bashrcfile
~/.bashrc
Shellscriptreadeachtimeabashshellisstarted Youcanusethisfiletodefine
Yourdefaultenvironmentvariables(PATH,EDITOR...). Youraliases. Yourprompt(seethebashmanualfordetails). Agreetingmessage.
80
Commandediting
Youcanusetheleftandrightarrowkeystomovethecursor inthecurrentcommand. Youcanuse[Ctrl][a]togotothebeginningoftheline, and[Ctrl][e]togototheend. Youcanusetheupanddownarrowstoselectearlier commands.
81
Commandhistory(1)
history Displaysthelatestcommandsthatyouranandtheirnumber. Youcancopyandpastecommandstrings. Youcanrecallthelatestcommand: !! Youcanrecallacommandbyitsnumber !1003 Youcanrecallthelatestcommandmatchingastartingstring: !cat
82
Commandhistory(2)
Youcanmakesubstitutionsonthelatestcommand: ^more^less Youcanrunanothercommandwiththesamearguments: more!*
83
TheUnixandGNU/Linuxcommandline
Miscellaneous
Texteditors
84
Texteditors
Graphicaltexteditors Fineformostneeds nedit Emacs,Xemacs Textonlytexteditors Oftenneededforsysadminsandgreatforpowerusers vi nano
85
Thenedittexteditor
http://www.nedit.org/ Besttexteditorfornonvioremacsexperts Featurehighlights:
Veryeasytextselectionandmoving Syntaxhighlightingformostlanguagesandformats.Canbe tailoredforyourownlogfiles,tohighlightparticularerrors andwarnings. Easytocustomizethroughmenus
Notinstalledbydefaultbyalldistributions
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
86
neditscreenshot
87
Emacs/Xemacs
EmacsandXemacsareprettysimilar (uptoyourpreference) Extremelypowerfultexteditorfeatures Greatforpowerusers Lessergonomicthannedit Nonstandardshortcuts Muchmorethanatexteditor (games,email,shell,browser). Somepowercommandshavetobe learnt.
88
vi
TextmodetexteditoravailableinallUnixsystems.Created beforecomputerswithmiceappeared. Difficulttolearnforbeginnersusedtographicaltexteditors. Veryproductiveforpowerusers. Oftencan'tbereplacedtoeditfilesinsystemadministration orinEmbeddedSystems,whenyoujusthaveatextconsole.
89
vimviimproved
viimplementationnowfoundinmostGNU/Linux hostsystems Implementslotsoffeaturesavailableinmodern editors:syntaxhighlighting,commandhistory,help, unlimitedundoandmuchmuchmore. Coolfeatureexample:candirectlyopencompressed textfiles. ComeswithaGTKgraphicalinterface(gvim) Unfortunately,notfreesoftware(becauseofasmall restrictioninfreedomtomakechanges)
90
vibasiccommands
Thoughviisextremely powerful,itsmain30 commandsareeasytolearn andaresufficientfor99%of everyone'sneeds! Youcanalsotakethequick tutorialbyrunning vimtutor. Getourvimementosheetifyoudidn'tgetitwiththiscourse: http://freeelectrons.com/training/intro_unix_linux
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
91
GNUnano
http://www.nanoeditor.org/ Anothersmalltextonly,mousefreetexteditor. AnenhancedPicoclone(nonfreeeditorinPine) Friendlyandeasiertolearnforbeginnersthankstoonscreen commandsummaries. Availableinbinarypackagesforseveralplatforms. Analternativetoviinembeddedsystems. However,notavailableasabusyboxbuiltin.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
92
GNUnanoscreenshot
93
TheUnixandGNU/Linuxcommandline
Miscellaneous
Compressingandarchiving
94
Measuringdiscusage
Caution:differentfromfilesize! duh<file>(diskusage) h:returnssizeondiskofthegivenfile,inhumanreadable format:K(kilobytes),M(megabytes)orG(gigabytes),. Withouth,dureturnstherawnumberofdiskblocksused bythefile(hardtoread). NotethatthehoptiononlyexistsinGNUdu. dush<dir> s:returnsthesumofdiskusageofallthefilesinthegiven directory.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
95
Measuringdiskspace
dfh<dir> Returnsdiskusageandfreespaceforthefilesystemcontaining thegivendirectory. Similarly,thehoptiononlyexistsinGNUdf. Example:
>dfh. FilesystemSizeUsedAvailUse%Mountedon /dev/hda59.2G7.1G1.8G81%/
96
Compressing
Veryusefulforshrinkinghugefilesandsavingspace g[un]zip<file> GNUzipcompressionutility.Creates.gzfiles. Ordinaryperformance(similartoZip). b[un]zip2<file> Morerecentandeffectivecompressionutility. Creates.bz2files.Usually2025%betterthangzip. Using7zip Muchbettercompressionratiothanbzip2(upto10to20%). Seethe7zippagefordetails.
97
Archiving(1)
Usefultobackuporreleaseasetoffileswithin1file tar:originallytapearchive Creatinganarchive: tarcvf<archive><filesordirectories> c:create v:verbose.Usefultofollowarchivingprogress. f:file.Archivecreatedinfile(tapeusedotherwise). Example: tarcvf/backup/home.tar/home bzip2/backup/home.tar
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
98
Archiving(2)
Viewingthecontentsofanarchiveorintegritycheck: tartvf<archive> t:test Extractingallthefilesfromanarchive: tarxvf<archive> Extractingjustafewfilesfromanarchive: tarxvf<archive><filesordirectories> Filesordirectoriesaregivenwithpathsrelativetothe archiverootdirectory.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
99
ExtraoptionsinGNUtar
tar=gtar=GNUtaronGNU/Linux Cancompressanduncompressarchivesonthefly.Usefulto avoidcreatinghugeintermediatefiles Muchsimplertodothanwithtarandbzip2! joption:[un]compressesontheflywithbzip2 zoption:[un]compressesontheflywithgzip Examples(whichonewillyouremember?)
gtarjcvfbills_bugs.tar.bz2bills_bugs tarcvfbills_bugs|bzip2>bills_bugs.tar.bz2
100
7zip(1)
http://www.7zip.org/ Nowthebestsolutionforyourarchives! License:GNULGPL 7zipcompressesmuchbetterthanbzip2(upto10or20%) andofcoursezip(30to50%). BenchmarkcompressingKnoppix5.0.1:22%(vs.bzip2)! Caution:7zipcannotreplacetarforarchivingonUnix. Itdoesn'tkeepfileownerandgroupinformation, butofcoursekeepsfilepermissions. Useittocompresstararchives!
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
101
7zip(2)
7zipsupportsstrongAES256encryption. Noneedtoencryptinaseparatepass. AtlastasolutionavailableforUnixandWindows! Thetoolsupportsmostothercompressionformats: zip,cab,arj,gzip,bzip2,tar,cpio,rpmanddeb.
102
Using7zip
Archivefilesareusuallycreatedwitha.7zextension Creatinganarchive:(a:add) 7za<archive><filesordirectories> Listfilesinarchive:(l:list) 7zl<archive> Extractingfroma7ziparchive:(e:extract) 7zx<archive> Backupadirectory(keepingownerandgroupinformation): tarcf<dir>|7zasidir.tar.7z Restorethisbackup: 7zxsodir.tar.7z|tarxf
standardoutput
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
standardinput
103
Checkingfileintegrity
Verylowcostsolutiontocheckfileintegrity md5sumFC3i386disk*.iso>MD5SUM ComputesaMD5(MessageDigestAlgorithm5)128bitchecksumofthe givenfiles.Usuallyredirectedtoafile. Exampleoutput: db8c7254beeb4f6b891d1ed3f689b412FC3i386disc1.iso 2c11674cf429fe570445afd9d5ff564eFC3i386disc2.iso f88f6ab5947ca41f3cf31db04487279bFC3i386disc3.iso 6331c00aa3e8c088cc365eeb7ef230eaFC3i386disc4.iso md5sumcMD5SUM CheckstheintegrityofthefilesinMD5SUMbycomparingtheiractualMD5 checksumwiththeiroriginalone.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
104
TheUnixandGNU/Linuxcommandline
Miscellaneous
Printing
105
Unixprinting
Multiuser,multijob,multiclient,multiprinter InUnix/Linux,printingcommandsdon'treallyprint.Theysendjobs toprintingqueues,possiblyonthelocalmachine,onnetworkprinting serversoronnetworkprinters. Printerindependentsystem: PrintserversonlyacceptjobsinPostScript ortext.Printerdriversontheservertake careoftheconversiontoeachprintersownformat. Robustsystem: Rebootasystem,itwillcontinuetoprintpendingjobs.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
106
Printingcommands
Usefulenvironmentvariable:PRINTER Setsthedefaultprinteronthesystem.Example: exportPRINTER=lp lpr[P<queue>]<files> Sendsthegivenfilestothespecifiedprintingqueue ThefilesmustbeintextorPostScriptformat.Otherwise,youonly printgarbage. a2ps[P<queue>]<files> AnytoPostScriptconvertsmanyformatstoPostScriptandsend theoutputtothespecifiedqueue.Usefulfeatures:severalpages/ sheet,pagenumbering,infoframe...
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
107
Printjobcontrol
lpq[P<queue>] Listsalltheprintjobsinthegivenordefaultqueue.
lpisnotready RankOwnerJobFile(s)TotalSize 1stasloane84nsa_windows_backdoors.ps60416bytes 2ndamoore85gw_bush_iraq_mistakes.ps65024000bytes
cancel<job#>[<queue>] Removesthegivenjobnumberfromthedefaultqueue.
108
UsingPostScriptandPDFfiles
ViewingaPostScriptfile PostScriptviewersexist,buttheirqualityisprettypoor. BetterconverttoPDFwithps2pdf: ps2pdfdecss_algorithm.ps xpdfdecss_algorithm.pdf& PrintingaPDFfile Youdon'tneedtoopenaPDFreader! BetterconverttoPostScriptwithpdf2ps: pdf2psrambaldi_artifacts_for_dummies.pdf lprrambaldi_artifacts_for_dummies.ps
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
109
TheUnixandGNU/Linuxcommandline
Miscellaneous
Comparingfilesanddirectories
110
Comparingfilesanddirectories
difffile1file2 Reportsthedifferencesbetween2files,ornothingifthefiles areidentical. diffrdir1/dir2/ Reportsallthedifferencesbetweenfileswiththesamenamein the2directories. Toinvestigatedifferencesindetail,betterusegraphicaltools!
111
tkdiff
http://tkdiff.sourceforge.net/ Usefultooltocomparefilesandmergedifferences
112
kompare
Anothernicetooltocomparefilesandmergedifferences Partofthekdesdkpackage(FedoraCore)
113
gvimdiff
Anothernicetooltoviewdifferencesinfiles
Availableinmost distributionswithgvim Apparentlynotusing diff. Noissuewithfileswith binarysections!
114
TheUnixandGNU/Linuxcommandline
Miscellaneous
Lookingforfiles
115
Thefindcommand
Betterexplainedbyafewexamples! find.name*.pdf Listsallthe*.pdffilesinthecurrent(.)directoryor subdirectories.Youneedthedoublequotestopreventtheshell fromexpandingthe*character. finddocsname"*.pdf"execxpdf{}';' Findsallthe*.pdffilesinthedocsdirectoryanddisplays oneaftertheother. Manymorepossibilitiesavailable!However,theabove2 examplescovermostneeds.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
116
Thelocatecommand
Muchfasterregularexpressionsearchalternativetofind locatekeys Listsallthefilesonyoursystemwithkeysintheirname. locate*.pdf Listsallthe*.pdffilesavailableonthewholemachine locate/home/fridge/*beer* Listsallthe*beer*filesinthegivendirectory(absolutepath) locateismuchfasterbecauseitindexesallfilesinadedicated database,whichisupdatedonaregularbasis. findisbettertosearchthroughrecentlycreatedfiles.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
117
TheUnixandGNU/Linuxcommandline
Miscellaneous
Variouscommands
118
Gettinginformationaboutusers
who Listsalltheusersloggedonthesystem. whoami TellswhatuserIamloggedas. groups TellswhichgroupsIbelongto. groups<user> Tellswhichgroups<user>belongsto. finger<user> Tellsmoredetails(realname,etc)about<user> Disabledinsomesystems(securityreasons).
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
119
Changingusers
Youdonothavetologouttologonanotheruseraccount! suhyde (Rare)Changetothehydeaccount,butkeepingthe environmentvariablesettingsoftheoriginaluser. sujekyll (Morefrequent)Logonthejekyllaccount,withexactly thesamesettingsasthisnewuser. su Whennoargumentisgiven,itmeanstherootuser.
120
Thewgetcommand
Insteadofdownloadingfilesfromyourbrowser,justcopyandpaste theirURLanddownloadthemwithwget! wgetmainfeatures httpandftpsupport Canresumeinterrupteddownloads Candownloadentiresitesoratleastcheckforbadlinks Veryusefulinscriptsorwhennographicsareavailable (systemadministration,embeddedsystems) Proxysupport(http_proxyandftp_proxyenv.variables)
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
121
wgetexamples
wgetc\ http://microsoft.com/customers/dogs/winxp4dogs.zip Continuesaninterrupteddownload. wgetmhttp://lwn.net/ Mirrorsasite. wgetrnphttp://www.xml.com/ldd/chapter/book/ Recursivelydownloadsanonlinebookforofflineaccess. np:"noparent".Onlyfollowslinksinthecurrentdirectory.
122
Misccommands(1)
sleep60 Waitsfor60seconds (doesn'tconsumesystemresources). wcreport.txt(wordcount) 438211518302report.txt Countsthenumberoflines,wordsandcharactersina fileorinstandardinput.
123
Misccommands(2)
bc("basiccalculator?") bcisahandybutfullfeaturedcalculator.Evenincludes aprogramminglanguage!Usetheloptiontohave floatingpointsupport. date Returnsthecurrentdate.Usefulinscriptstorecordwhen commandsstartedorcompleted.
124
TheUnixandGNU/Linuxcommandline
Systemadministrationbasics
125
Fileownership
Particularlyusefulin(embedded)systemdevelopment whenyoucreatefilesforanothersystem. chownRsco/home/linux/src(R:recursive) Makesuserscothenewownerofallthefilesin /home/linux/src. chgrpRempire/home/askywalker Makesempirethenewgroupofeverythingin /home/askywalker. chownRborg:aliensusss_entreprise/ chowncanbeusedtochangetheownerandgroupatthesametime.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
126
Shuttingdown
shutdownh+5(h:halt) Shutsthesystemdownin5minutes. Usersgetawarningintheirconsoles. shutdownrnow(r:reboot) init0 Anotherwaytoshutdown (initisusedinternallybyshutdown). init6 Anotherwaytoreboot. [Ctrl][Alt][Del] AlsoworksonGNU/Linux(atleastonPCs!).
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
127
Networksetup(1)
ifconfiga Printsdetailsaboutallthenetworkinterfacesavailable onyoursystem. ifconfigeth0 Listsdetailsabouttheeth0interface ifconfigeth0192.168.0.100 Assignsthe192.168.0.100IPaddress toeth0(1IPaddressperinterface). ifconfigeth0down Shutsdowntheeth0interface (freesitsIPaddress).
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
128
Networksetup(2)
routeadddefaultgw192.168.0.1 Setsthedefaultrouteforpacketsoutsidethelocalnetwork. Thegateway(here192.168.0.1)isresponsiblefor sendingthemtothenextgateway,etc.,untilthefinal destination. route Liststheexistingroutes routedeldefault routedel<IP> Deletesthegivenroute Usefultoredefineanewroute.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
129
Networktesting
pingfreshmeat.net ping192.168.1.1 Triestosendpacketstothegivenmachineandgetacknowledgment packetsinreturn.
PING192.168.1.1(192.168.1.1)56(84)bytesofdata. 64bytesfrom192.168.1.1:icmp_seq=0ttl=150time=2.51ms 64bytesfrom192.168.1.1:icmp_seq=1ttl=150time=3.16ms 64bytesfrom192.168.1.1:icmp_seq=2ttl=150time=2.71ms 64bytesfrom192.168.1.1:icmp_seq=3ttl=150time=2.67ms
130
Networksetupsummary
Onlyforsimplecaseswith1interface,nodhcpserver... Connecttothenetwork(cable,wirelesscardordevice...) Identifyyournetworkinterface: ifconfiga AssignanIPaddresstoyourinterface(assumingeth0) ifconfigeth0192.168.0.100(example) Addaroutetoyourgateway(assuming192.168.0.1)for packetsoutsidethenetwork: routeadddefaultgw192.168.0.1
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
131
Nameresolution
YourprogramsneedtoknowwhatIPaddresscorrespondstoa givenhostname(suchaskernel.org) DomainNameServers(DNS)takecareofthis. YoujusthavetospecifytheIPaddressof1ormoreDNS serversinyour/etc/resolv.conffile: nameserver217.19.192.132 nameserver212.27.32.177 Thechangestakeseffectimmediately!
132
Creatingfilesystems
Examples mkfs.ext2/dev/sda1 FormatsyourUSBkey(/dev/sda1:1stpartitionrawdata)inext2format. mkfs.ext2Fdisk.img Formatsadiskimagefileinext2format mkfs.vfatvF32/dev/sda1(v:verbose) FormatsyourUSBkeybacktoFAT32format. mkfs.vfatvF32disk.img FormatsadiskimagefileinFAT32format. Blankdiskimagescanbecreatedasinthebelowexample: ddif=/dev/zeroof=disk.imgbs=1024count=65536
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
133
Mountingdevices(1)
Tomakefilesystemsonanydevice (internalorexternalstorage) visibleonyoursystem,youhavetomountthem. Thefirsttime,createamountpointinyoursystem: mkdir/mnt/usbdisk(example) Now,mountit: mounttvfat/dev/sda1/mnt/usbdisk /dev/sda1:physicaldevice t:specifiesthefilesystem(format)type (ext2,ext3,vfat,reiserfs,iso9660...)
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
(filedescriptors andfilecontents)
rawdata
mount
file structure
134
Mountingdevices(2)
Lotsofmountoptionsareavailable,inparticulartochoosepermissionsorthe fileownerandgroup...Seethemountmanualpagefordetails. Mountoptionsforeachdevicecanbestoredinthe/etc/fstabfile. Thankstothisfile,youjustneedtostatethemountpoint:
#/etc/fstab:staticfilesysteminformation. #<filesystem><mountpoint><type><options> <dump><pass> proc/procprocdefaults 00 /dev/hda3/ext3defaults,errors=remountro 01 /dev/hda4/homeext3defaults 02 /dev/hda2/root2ext3defaults 02 /dev/hda1noneswapsw 00 /dev/hdc/media/cdrom0udf,iso9660user,noauto 00
135
Mountingdevices(3)
Youcanalsomountafilesystemimage storedinaregularfile(loopdevices) Usefultodevelopfilesystemsforanothermachine UsefultoaccessthecontentsofanISOcdromimagewithouthavingto burnit. UsefultocreateaLinuxpartitiononaharddisk withonlyWindowspartitions cp/dev/sda1usbkey.img mountolooptvfatusbkey.img/mnt/usbdisk
136
Listingmountedfilesystems
Justusethemountcommandwithnoargument:
/dev/hda6on/typeext3(rw,noatime) noneon/proctypeproc(rw,noatime) noneon/systypesysfs(rw) noneon/dev/ptstypedevpts(rw,gid=5,mode=620) usbfson/proc/bus/usbtypeusbfs(rw) /dev/hda4on/datatypeext3(rw,noatime) noneon/dev/shmtypetmpfs(rw) /dev/hda1on/wintypevfat(rw,uid=501,gid=501) noneon/proc/sys/fs/binfmt_misctypebinfmt_misc(rw)
Ordisplaythe/etc/mtabfile (sameresult,updatedbymountandumounteachtimetheyarerun)
137
Unmountingdevices
umount/mnt/usbdisk Commitsallpendingwritesandunmountsthegivendevice, whichcanthenberemovedinasafeway. Tobeabletounmountadevice,youhavetocloseallthe openfilesinit:
Closeapplicationsopeningdatainthemountedpartition Makesurethatnoneofyourshellshaveaworkingdirectoryin thismountpoint. Youcanrunthelsofcommand(listopenfiles)toview whichprocessesstillhaveopenfilesinthemountedpartition.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
138
Bewareofthedarksideofroot
rootuserprivilegesareonlyneededforveryspecific taskswithsecurityrisks:mounting,creatingdevicefiles, loadingdrivers,startingnetworking, changingfileownership,packageupgrades... Evenifyouhavetherootpassword,yourregularaccount shouldbesufficientfor99.9%ofyourtasks (unlessyouareasystemadministrator). Inatrainingsession,itisacceptabletouseroot. Inreallife,youmaynotevenhaveaccesstothisaccount, orputyoursystemsanddataatriskifyoudo.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
139
Usingtherootaccount
Incaseyoureallywanttouseroot... Ifyouhavetherootpassword: su(switchuser) Inmoderndistributions,thesudocommandgivesyouaccesstosomeroot privilegeswithyourownuserpassword. Example:sudomount/dev/hda4/home DistributionslikeDebianorUbuntubydefaultdon'tallowtherootusertouse graphicalapplications(morecomplexandthusmorevulnerable). Ifyoureallywanttostartagraphicalapplicationwithroot,type: Asroot:exportDISPLAY=:0(i.e.usethefirstdisplay) Asyourregularuser:xhost+(i.e.allowotherusers)
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
140
TheUnixandGNU/Linuxcommandline
GNU/Linux:distributionpackages
141
Howtofindpackages
Debianpackages:http://www.debian.org/distrib/packages Searchbypackageorfilename rpmfind:http://rpmfind.net/ LotsofRPMpackagesforRedHat,Mandriva,Suse...
142
Identifyingpackages
Whatpackagedoesafilebelongto? Usefultogetmoreinformation,getthecode,findnewer versions,reportissues... DistributionwithRPMpackages: (RedHat,Fedora,Mandriva,Suse...) >rpmqf/bin/ls coreutils5.2.17 Debian,Ubuntu: >dpkgS/bin/ls fileutils:/bin/ls
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
143
Informationaboutpackages
Accesspackagedescription,versionnumber,sources,etc. RPMbaseddistributions: rpmqi<packagename> Debian: dpkgs<packagename>
144
TheUnixandGNU/Linuxcommandline
Goingfurther
145
Commandhelp
SomeUnixcommandsandmostGNU/Linuxcommandsoffer atleastonehelpargument: h (ismostlyusedtointroduce1characteroptions) help (isalwaysusedtointroducethecorrespondinglong optionname,whichmakesscriptseasiertounderstand) Youalsooftengetashortsummaryofoptionswhenyouinput aninvalidargument.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
146
Manualpages
man<keyword> Displaysoneorseveralmanualpagesfor<keyword> manman MostavailablemanualpagesareaboutUnixcommands,butsome arealsoaboutCfunctions,headersordatastructures,orevenabout systemconfigurationfiles! manstdio.h manfstab(for/etc/fstab) Manualpagefilesarelookedforinthedirectoriesspecifiedbythe MANPATHenvironmentvariable.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
147
Infopages
InGNU,manpagesarebeingreplacedbyinfopages.Some manualpageseventelltorefertoinfopagesinstead. info<command> infofeatures:
Documentationstructuredinsections(nodes)andsubsections (subnodes) Possibilitytonavigateinthisstructure:top,next,prev,up InfopagesgeneratedfromthesametexinfosourceastheHTML documentationpages
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
148
SearchingtheInternetforresources(1)
Investigatingissues Mostforumsandmailinglistarchivesarepublic,andare indexedonaveryfrequentbasisbyGoogle. Ifyouinvestigateanerrormessage,copyitverbatiminthe searchform,enclosedindoublequotes(errormessage).Lots ofchancesthatsomebodyelsealreadyfacedthesameissue. Don'tforgettouseGoogleGroups:http://groups.google.com/ Thissiteindexesmorethan20yearsofnewsgroupsmessages.
149
SearchingtheInternetforresources(2)
Lookingfordocumentation
Lookfor<tool>or<tool>pagetofindthetoolorproject homepageandthenfindthelatestdocumentationresources. Lookfor<tool>documentationor<tool>manualin yourfavoritesearchengine.
Lookingforgenerictechnicalinformation
WikiPedia:http://wikipedia.org Lotsofusefuldefinitionsincomputerscience.Areal encyclopedia!Opentoanyone'scontributions.
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
150
Traininglabs
Traininglabsarealsoavailablefromthesamelocation: http://freeelectrons.com/training/intro_unix_linux Theyareausefulcomplementtoconsolidate whatyoulearnedfromthistraining.Theydon'ttell howtodotheexercises.However,theyonlyrely onnotionsandtoolsintroducedbythelectures. Ifyouhappentobestuckwithanexercise,thisprovesthatyoumissed somethinginthelecturesandhavetogobacktotheslidestofindwhat you'relookingfor.
151
Relateddocuments
AllthetechnicalpresentationsandtrainingmaterialscreatedandusedbyFreeElectrons, availableunderafreedocumentationlicense(morethan1500pages!). http://freeelectrons.com/training
IntroductiontoUnixandGNU/Linux EmbeddedLinuxkernelanddriverdevelopment FreeSoftwaretoolsforembeddedLinuxsystems AudioinembeddedLinuxsystems MultimediainembeddedLinuxsystems LinuxUSBdrivers RealtimeinembeddedLinuxsystems IntroductiontouClinux LinuxonTIOMAPprocessors FreeSoftwaredevelopmenttools JavainembeddedLinuxsystems IntroductiontoGNU/LinuxandFreeSoftware Linuxandecology What'snewinLinux2.6? HowtoportLinuxonanewPDA
http://freeelectrons.com/articles
AdvantagesofFreeSoftwareinembeddedsystems EmbeddedLinuxoptimizations EmbeddedLinuxfromScratch...in40min!
152
Howtohelp
Ifyousupportthiswork,youcanhelp... Bysendingcorrections,suggestions,contributionsandtranslations Byaskingyourorganizationtoordertrainingsessionsperformedby theauthorofthesedocuments(seehttp://freeelectrons.com/training) Byspeakingaboutittoyourfriends,colleagues andlocalFreeSoftwarecommunity. Byaddinglinkstoouronlinematerialsonyourwebsite, toincreasetheirvisibilityinsearchengineresults.
153
Thanks
TotheOpenOffice.orgproject,fortheirpresentationand wordprocessortoolswhichsatisfiedallmyneeds. TotheHandhelds.orgcommunity,forgivingmesomuch helpandsomanyopportunitiestohelp. TothemembersofthewholeFreeSoftwareandOpen Sourcecommunity,forsharingthebestofthemselves:their work,theirknowledge,theirfriendship. Topeoplewhosentcommentsandcorrections: TylerLe,LaurentThomas,JeffGhislain,LeifThande, FrdricDesmoulins,PrzemysawCiesielski
TheUnixandGNU/Linuxcommandline Copyright20042007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license Jan25,2013 http://freeelectrons.com
154
EmbeddedLinuxTraining UnixandGNU/Linuxbasics Linuxkernelanddriversdevelopment RealtimeLinux uClinux Developmentandprofilingtools Lightweighttoolsforembeddedsystems Rootfilesystemcreation Audioandmultimedia Systemoptimization Consulting Helpindecisionmaking Systemarchitecture Identificationofsuitabletechnologies Managinglicensingrequirements Systemdesignandperformancereview
FreeElectronsservices
CustomDevelopment Systemintegration EmbeddedLinuxdemosandprototypes Systemoptimization Linuxkerneldrivers Applicationandinterfacedevelopment
http://freeelectrons.com