View
48
Download
1
Category
Preview:
Citation preview
LinuxCommandLine
(CoverAllEssentialLinuxCommands)
ABeginner’sGuide
ByRayYao
Copyright©2014byRayYaoAllRightsReservedNeitherpartofthisbooknorwholeofthisbookmaybereproducedortransmittedinanyformorbyanymeanselectronic,photographicor
mechanical,includingphotocopying,recording,orbyanyinformationstorageorretrievalsystem,withoutpriorwrittenpermissionfromtheauthor.
RayYao
AbouttheAuthorRayYao:CertifiedPHPengineerbyZend,USACertifiedJAVAprogrammerbySun,USACertifiedSCWCDdeveloperbyOracle,USACertifiedA+professionalbyCompTIA,USACertifiedASP.NETexpertbyMicrosoft,USACertifiedMCPprofessionalbyMicrosoft,USACertifiedTECHNOLOGYspecialistbyMicrosoft,USACertifiedNETWORK+professionalbyCompTIA,USA
PrefaceThis book is a beginner’s guide for fast learning Linux commandswhich are frequently used by Linuxadministrators or beginners. The book covers all essential Linux commands as well as their operations,examplesandexplanations. Italso includesLinuxHelpingcommands,symbols,shortcutkeys, run levelsandVicommands.Fromthisbook,youcaneasilylearn:HowtorunallessentialLinuxcommands.Howtocopy,move,anddeletefilesanddirectories.Howtocreate,remove,andmanageusersandgroups.HowtoaccessLinuxserver,anduseSSHcommands.HowtooperatetherunlevelsandchangetherunlevelsHowtonavigateatthecommandlinebyhelpingcommands.Howtocomparefiles,findoutafile,manipulatefilecontentsHowtostartajob,stopajobandscheduleajob.Howtomanagepermissions,ownershipoffiles,directoriesHowtoconnectacrossnetwork,communicatewithnetwork.Howtotransferfilesovernetwork,sendnetworkmessagesAndmuchmoreskill……ThereisalongtablecontainingallcommonLinuxcommandsinthisbook,whichcangiveyouagreathelpinyourjoborstudy.YoucanlearnallessentialLinuxcommandsquickly.
TableofContents
Chapter1IntroductiontoLinux6Chapter2EnterFirstCommandsChapter3SuperUserCommandsChapter4NavigatingAtCommandsChapter5FileOperationCommands39Chapter6ViewingFileCommandsChapter7ComparingFileCommandsChapter8MatchingTextCommandsChapter9DirectoryCommandsChapter10Un/CompressCommands59Chapter11ProcesseCommandsChapter12AccountCommandsChapter13GroupsCommands68Chapter14PermissionCommandsChapter15RunningJobCommandsChapter16Backup/RestoreCommandsChapter17Date&TimeCommands79Chapter18NetworkingCommandsChapter19ScriptingCommandsChapter20SystemCommandsChapter21HelpingCommandsChapter22SkillofCommands98Chapter23AccessPermissionsChapter24LinuxSymbolsChapter25ShortcutKeysChapter26RunLevelsTableChapter27TheViEditorCommandsChapter28AllEssentialLinuxCommandsConclusion
Chapter1IntroductiontoLinux
AboutLinuxOperatingSystemLinux is aUnix-like andmostly POSIX-compliant computer operating systemassembledunder themodelof freeandopen-sourcesoftwaredevelopmentanddistribution.Linuxusuallyworksasaserver,becauseofitsstabilityandsecurity’sfeature.Linuxprogramsareextremelyadvantageous:
Linuxprogramsarefree,you’llsee,mostofLinuxprogramsare.TheyarefrequentlyupdatedandforZerocharge!Someofthemarebetterthanthoseinwindows.Andotherdoesn’tevenexistinwindows!
If Linux is free and almost all their softwares are free, it is for a reason; tounderstandwehavetogobackto1984.
1984Sowe are back in 1984, computer sciencewasnot verydeveloped.Microsofthasjustlauncheditsfirstos:MS-DOS,butthisoneisfarawayfrombeingdone.
But,wasMS-DOStheonlyonethen?
No!Therewasotheroperatingsystembutlessknownbythepublic.Theonethatwascalledthebestwas“Unix”.ItwasalotpowerfulthanMS-DOSbutalotcomplicated,whatexplainsthatonlytheprofessionalscoulduseit.GraphicallyUNIXlookeda lot likeMS-DOStheywerebothseenlikeablackscreenwithsomewhite text in it.Wemustsay thatcomputersback thenwerenotcapableofdoingbetter.
GNUProjectItisjustin1984,thatRichardStallmancreatedGNUproject.TheGNUProjectisfreesoftware,masscollaborationproject,announcedon27September1983,byRichardStallmanatMIT.Itsaimistogivecomputerusersfreedomandcontrol in theiruseof theircomputersandcomputingdevices,bycollaborativelydevelopingandprovidingsoftwarethatisbasedonthefollowing
freedom rights: users are free to run the software, share it (copy, distribute),study it andmodify it. GNU software guarantees these freedom-rights legally(viaitslicense),andisthereforefreesoftware;theuseoftheword"free"alwaysbeingtakentorefertofreedom.RichardStallmanwasaresearcherinArtificialintelligenceinMIT.HewantedtocreateanoperatingsystembasedonUNIX(thecommandsstillthesame).Butwhywouldhecreateacopyof“UNIX”?Because UNIX was not free and it was getting more expensive! RichardStallmanwanted to react by creating a free alternative: the project GNUwasborn.
GNUisanopenoperatingsystemGNUshouldnotonlybeafreeOS;italsohadtobe"open"Whatisthedifference?Afreeprogramisaprogramwhereyoucanhavethesourcecode,thatistosay,the"batchrecipe."Incontrast,WindowsisaproprietaryOSwhosesourcecodeis stored byMicrosoft. Imagine it's like Coca-Cola: nobody knows the recipe(therearemanypeoplewhotrytoimitateit,buthey...).Sowecannotchangeitorseehowitworksinside.Anopenprogramismostlyafreeprogram,itisalsoaprogramthathastherightto copy,modify, redistribute. It's a real ideology in computer science: peoplethinkitisbettertogivethesourcecodeoftheprogramsthatwecreatebecauseitallowsknowledgesharingandhelpsthecomputertoevolvefaster.ThesloganoftheFreeWorldmightbe:"Unityisstrength."They say whenever the program is "open source" because its source code isopen; everyone can see it. There are some slight differences between "opensource"programanda"free"program,butwewillnotgointodetailshere.
LinusTorvaldsisdoinghishobbyIn1991,LinusTorvalds,astudentattheUniversityofHelsinki(Finland),begancreating his free own operating system.This systembecame known asLinux,referringtothenameofitscreator(LinuxisacontractionofLinusandUNIX).
LinusTorvalds,creatorofLinuxWhat relationship with GNU?Well it turns out that these two projects werecomplementary: while Richard Stallman created the basic programs (program
file copy, delete, file, text editor), Linus had embarked on the creation of the"heart"anoperatingsystemkernel.TheGNU(freeprograms)andLinux(OSkernel)projectmergedtocreateGNU/Linux.Theoretically,weshouldtalkaboutGNU/Linux.Butitisabitdifficulttowriteandpronounce,andbyabuseoflanguage,weoftensayjust"Linux".ThisiswhyIcontinuetospeakof"Linux"intherestofthebook,eventhoughthepoliticallycorrectnameis"GNU/Linux"becauseitisthemergeroftwocomplementaryprojects.
OriginaloperatingsystemsYou should now have a better idea of the origin of the threemajor operatingsystemsthatexisttoday:MacOS,LinuxandWindows.Thus,MacOS and Linux are both based onUNIX, the ancestor of operatingsystems,whileWindows,fromMS-DOSisaseparatebranch.Overall,thisisallyouneedtoremember.ItissaidthatMacOSandLinuxarebasedonUNIXbecausetheyhave"copied"its operation. It's not pejorative, it’s quite the opposite: it's been an honor toUNIX.Linuxprogramsdonotuseall thesamesourcecodeasUNIX(itwasalso theowner,soprivate).Theyhavebeencompletelyrewrittenbutworkthesameway.If I told you all this is because I believe that knowing the origin of Linux isimportant.Thiswillhelpyouunderstandmanythingsthereafter.
LinuxdistributionsALinuxdistribution(oftencalleddistroforshort)isanoperatingsystemmadeas a collection of software based around the Linux kernel and often around apackagemanagement system. ThemostwellknowndistributionsareRedHat,SUSE,Debian,Mandriva,SlackwareandUbuntu.Youcanfindmuchdifferentsoftwareandtherearehundredsofdifferentwaystoinstallit.Tomakelifeeasierforusersandallowthemtomakeachoice,differentLinuxdistributions were created. This is a concept that does not really exist inWindows. It's like the difference betweenWindows 7 Home andWindows 7Professional,butitgoesmuchfurtherthanthat.
Here'swhatcandifferfromonedistributiontoanother:Installation:itcanbegreatlysimplifiedasverycomplicated;Installingmanagement programs: If it is donewell and centralized, it
canmake the installation of new software simpler thanWindows, asdiscussedfurther!Thepreinstalledprogramsonyourcomputer(e.g.WindowsisbundledwithInternetExplorerandWindowsMediaPlayer).
Infact,distributionissomehowpackingLinux.Theheartitselfremainsthesameforalldistributions.Whichever distribution you install, you get a Linux compatible with others.Somedistributionsarejustmoreorlesseasytohandle.:-)
VariousexistingdistributionsThere are many different Linux distributions. Hard to choose , you will say:indeed,thefirsttimeitisunclearwhattochoose...especiallysinceallarefree!Donotworry;I'llhelpyoumakeyourchoice.Iwillnotlistallexistingdistributions,buthereatleastthemainones:Slackware:oneoftheoldestLinuxdistributions.Itstillexiststoday!Mandriva:publishedbyaFrenchcompany,itissimpletouse;RedHat: published by an American company, this distribution is known andwidespread,especiallyonservers;SUSE:Novellpublishedbythecompany;Debian:Debiandistributionalonewhichismanagedbyindependentdevelopersratherthanabusiness.Thisisoneofthemostpopulardistributions.AsIhavesaid,whateverthedistro(shortfordistribution)youchoose,youwillhave a Linux. Basically, "just" a screen on first boot and various softwarepreinstalled(I'msimplifyingabitmuch,buttheideaisthere).
SummaryWindows,MacOSandLinuxarethemostpopularoperatingsystems.Linuxusuallyworksasaserver,becauseofitsstabilityandsecurity’sfeature.Linux has the distinction of being free, that is to say that its source code (themanufacturingrecipe)isopen:anyonecanviewit.Incontrast, thesourcecodethatwasusedtodesignWindowsandMacOSisclosed;wesaythat theseareproprietaryoperatingsystems.TherearemanyvariantsofLinux,calleddistributions.
Chapter2EnterFirstCommands
Dear friends, thebigdayhas finally arrived!Youwill get the chance towriteyourfirstcommandinconsole!Okay,nottoostressed?
I assure you, we will start with simple things to become familiar with theconsole.We'llreallyseetheABC,thebasicsurvivalguideofkits.
WhatistheLinuxshell?ALinuxshell isacommand-line interpreterorshell thatprovidesa traditionaluserinterfacefortheLinuxoperatingsystemandforLinux-likesystems.Theshellunderstandsaplentyofshellcommandsanditsoptionwhichchangetheiraction.Thetypicalsyntaxofsellcommandlooks like this:command –optionargumentorcommandparameter(Usually–optionargumentmeansparameter)Commandsuchas:ls,cat,pwd,cp,mv,date……Parametersuchas:-a,-l,-s,--all,--help……Example:ls–aExplanation:lsisacommandmeaninglistthecontentsincurrentdirectory-aisaparametermeaning“all”.Result:listallcontentsincurrentdirectory.Shell commands can be run at a prompt in text interface mode or in a shellterminalwindow.The command prompts with shell command show something like this:username@hostname:~$commandparameterroot@hostname:~#commandparameteruser>commandparameter
Explanation:
Whatyouseehereiscalledthecommandprompt.Itisamessagethatpromptsyou to enter a commandby giving you at the same time a lot of information.Thiscommandpromptisdisplayedbeforeeachcommandyoutype.
“username@hostname:~$”isacommandprompt.“root@hostname:~#”isacommandprompttoo.“user>”isacommandpromptaswell.
Aboutthe“username@hostname:~$ls”
Example:user2014@user-linux:~$ls
Explanation:
user2014:thefirstelementisyournickname.Thisistheusernameunderwhichyou are logged and you. Indeed, remember: you can create multiple useraccountsonLinux.Itisgenerallyadvisabletogenerateapersonwho’slikelytousethecomputer.@:Thissymbolindicatesnothingspecial.It'sthesymbol"at"user-linux: that's thenameof thecomputeronwhichyouareworking. Inmycaseitiscalleduser-linux,butIcouldgiveitanynameduringinstallation.:Again,thissymboldoesnotmeananythingspecial,itisaseparator.~: That's the folderwhere you currently are.You can navigate from folder tofolder in the console and it is veryuseful that you alwaysbe remindedwhereyouarebeforeeachcommand.For information, the symbol~means thatyouare inyourhomedirectory, so-called"home"underLinux;thisisequivalenttothe"MyDocuments"folderonWindows.WewillstudyindetailtheoperationofthefilesinLinuxinthenextchapter.$: That symbol is very important; it shows your authorization level on themachine.ls:lsisacommand,showthecontentsofcurrentdirectory.
Moredetailabout$$:Meansyouarecurrentlyusingauser"normal"accountwithlimitedrights(hecannot change the most important system files). My account user2014 is anormal accountwith limited rights; As you can see, oncewe speak the samelanguageasthecommandprompt,youunderstandwhatitmeans!"Welcome,youareuser2014atuser-linuxmachine.Youare currently inyourhomedirectoryandhave limiteduserrights.Youareusingacommand“ls” tolistthecontentsincurrentdirectory."
Aboutthe“root@hostname:~#whoami”Example:root@user-linux:~#whoamiExplanation:root:meansuserworkasasuperuser@:Thissymbolindicatesnothingspecial.It'sthesymbol"at"user-linux: that's thenameof thecomputeronwhichyouareworking. Inmycaseitiscalleduser-linux,butIcouldgiveitanynameduringinstallation.:Again,thissymboldoesnotmeananythingspecial,itisaseparator.~: That's the folderwhere you currently are.You can navigate from folder tofolder in the console and it is veryuseful that you alwaysbe remindedwhereyouarebeforeeachcommand.For information, the symbol~means thatyouare inyourhomedirectory, so-called"home"underLinux;thisisequivalenttothe"MyDocuments"folderonWindows.WewillstudyindetailtheoperationofthefilesinLinuxinthenextchapter.#:meansyouareworkinginsuperusermodeWhoami:whoamiisacommand,showthecurrentusernameMoredetailabout##:Meansyouareinsuperusermode,thatistosaythatyouareconnectedunderthepseudonym"root."Therootisthemasterwhohastherighttodoeverythingon his computer user (even to destroy it!).We'll see how root inmore detaillater; yet we remain in a limited user account, so we do not risk doing badthings."Welcome,youaresuperuseratuser-linuxmachine.Youarecurrentlyinyour
homedirectoryandhavesuperuserrights.Youareusingacommand“whoami”toshowthecurrentusername."
About“user>pwd”Example:user>pwdExplanation:user>:isacustomizedcommandprompt.pwd:pwdisacommand,printworkingdirectory.You can customize the command prompt like user>. Of course after you arefamiliarwithLinuxcommandprogramming,youwillbeable tocustomize theshellprompt.Atthismoment,theLinuxmachinewillsayhallotoyou:"Welcome,youareauseratuser-linuxmachine.Youarecurrently inyourhomedirectoryandhavelimited user rights. You are using the “pwd” command to print workingdirectory."AsabitofeverythingonLinux,thecommandpromptisfullyconfigurable.Youcanshortenitifyoufinditistoolong,orlengthenitifitdoesnotgiveenoughinformation.Youcantheoreticallyputreallyeverythingyouwantintheprompt,suchasthecurrenttime.Workingintheconsolebytypingcommands,thelatterbeingnumerous,youcanneverknowallof them ... and it isnot thegoal: thegoal is thatyouknowbyhearttoservethemost"common"onesandforthelesscommonyouareabletolearntousethembyreadingtheirmanual.
AboutLinuxcommandsThe typical syntax of sell command looks like this: command –option argumentorcommandparameter
Let’sseesomeexampleofcommandsandparameters:Example:Type“date”andpresstheEnterkey.user2014@user-linux:~$dateMonday,September20,2010,3:39:51p.m.(UTC-0200)Explanation:ThefirstlinecontainsthecommandpromptfollowedcommandItyped.Inhere,“date”isacommand.Thesecondlineisthecomputerresponsetothiscommand:weaskedaboutthedateandtime!
AboutParametersParameters are options that arewritten after the command.The command andparameters are separated by a space, like this: user2014 @ user-linux: ~ $commandparameters The parameters themselves can contain spaces, letters,numbers...abitofeverything,really.Thereisnorealruleonhowthesettings,butfortunatelyprogrammershaveadoptedasortof"agreement"sothatwecanrecognizethedifferenttypesofparameters.
Shortparameters(oneletter)Themost commonparameters are constituted by a single letter preceded by adash.Forinstance:-d-l-aIfwehavetogiveseveralparameters,youcandoitlikethis:-d-a-U-hOrshorter:-daUhBEWARE!Forshortparameters:aparameterindifferentcommandhasdifferentmeanings.Example:ls-t(-tmeans“listbytimestamps”.)eject-t(-tmeans“trayclose”.)chfn -f (-fmeans”change informationby fingername”)cut -f (-fmeans“cut
textbyafieldnumber”)ps-f(-fmeans“showprocessstatusinfullinformation”)BEWARE!Parameteriscasesensitive(upper/lowercase).Ifyouwrite-u,thishasgenerallynotthesamesenseas–U.Doesatestwiththelscommand,andwriteittheparameter"-a"(lowercase),-ameans“all”:Example:user2014@user-linux:~$ls-a..gconfd .mozilla-thunderbird .. gimp-2.2 .nautilus .bash_history .gksu.lock.profile.bash_logout.gnome.recently-used.bashrc.gnome2.recently-used.xbel.config .gnome2_private .ssh Desktop .gstreamer- .sudo_as_admin_successful.dmrc .gtkrc 0.10-1.2-gnome2 .themes .esd_auth .ICEauthority .thumbnails.evolution.icons.TrashExamples.lesshsttutorials.face.local.update-manager-core.fontconfig.macromedia.update-notifier.gaim.metacity.Xauthority.gconf.mozilla.xsession-errorsThisdisplaysallfilesofcurrentdirectory,evenhiddenfiles.A"cookie"isaLinuxfilethatbeginswithaperiod.Normally,ifyou'reinyourhomedirectory,youshouldhaveagoodbunchofhiddenfiles.Theseareusuallyconfigurationfilesprogram.Long parameters (severalletters) The parameters consist ofseverallettersareprecededbytwodashes,likethis:--longparameterForinstance:--all--allisalongparameter,meaningallcontentsorallthings.Forinstance:--version--versionisalongparameter,meaningtheversionofthecommandForinstance:--help--helpisalongparameter,meaninggethelpforcurrentcommand.Ifyouwanttoputseveralfeatureparameters, itwilladdaspacebetweeneachone:Command--longparametre1--longparametre2One can also combine the long and short parameters in control parameters:Command-daUh--AllSometimestherearetwopossibleentriesforacontrolparameter:ashortversionand a long version. Thiswill let you choosewhichever you prefer one or theother.Notethatthisisthecommandthatdecidestheparametersitaccepts:sometimessomedonotofferachoicebetweenashortversionandalong.Let's test this on the ls command with the --all parameter, which means"everything":Example:
user2014@user-linux:~$ls--all..gconfd .mozilla-thunderbird .. gimp-2.2 .nautilus .bash_history .gksu.lock.profile.bash_logout.gnome.recently-used.bashrc.gnome2.recently-used.xbel.config .gnome2_private .ssh Desktop .gstreamer- .sudo_as_admin_successful.dmrc .gtkrc 0.10-1.2-gnome2 .themes .esd_auth .ICEauthority .thumbnails.evolution.icons.TrashExamples.lesshsttutorials.face.local.update-manager-core.fontconfig.macromedia.update-notifier.gaim.metacity.Xauthority.gconf.mozilla .xsession-errors As you can see, is a synonym for --all -a. Thisillustrateswhat I saidamomentago,whichshows thatsometimesacommandofferstwowaystouseaparameter:ashortandalong.
******
CommandsandParametersExamplesOK!Let’shaveafurtherlookaboutthecommandsandtheirparameters.su–l:switchuserExample:user>su–l(su:goingtologinastherootsuperuser,-l:isaparametermeaning“login”)ls–l:listlongcontentsExample:user>ls–l(ls:showsthecontentsofcurrentdirectory.–l:isaparametermeaning“longlistincludeaccesspermissions,ownershipanddate&time.”)ls–a:listallcontentsExample:user>ls–a(ls:showsthecontentsofcurrentdirectory.–a: is a parameter meaning “all contents” including hidden files.) rm –ri :removeadirectoryanditscontentsExample:user>rm–riNonEmptyDir(rm:removesafileoradirectory.
–ri:isaparametermeaningremoveanon-emptydirectoryanditscontents.NonEmptyDirisadirectoryname.)w–s:showcurrentprocessforeachuserExample:user>w-s(w:showstheshellworkingprocesses.–s:isaparametermeaning“summary”)usermod–l:modifyanexistinguseraccount.Example:user>usermod–loldnamenewname(usermod:modifyanexistinguseraccount.–l:isaparametermeaning“loginnamechange”)
******
WhatisVirtualConsole?VirtualConsolemeansaninterfacewheretheinputdeviceandtheoutputdevicedesignedtoenableyoutointeractwithyoursystem.Linuxhas7virtualconsoles,youcanswitchthemusingCtrl+Alt+F1throughF7.Ctrl+Alt+F1~F6:switchvirtualconsole1~virtualconsole6Ctrl+Alt+F7:entergraphicaldesktop,whichisdefaultvirtualconsole.
Summary:
1.Whenuserisanormaluser,use:
username@hostname:~$commandparameter
2.Whenuserisasuperuser,use:
root@hostname:~#commandparameter
3.When the shell prompt has been customized, use: User> commandparameter
4.Linuxcommand:ls,pwd,su,whoami,loginname,rm,exit…
5.Commandparameter:-a,-ri,-l,--all,--help…6.VirtualConsole:letyouhaveseveralinterfaceshellsessionsactiveatthesametime.
Chapter3SuperUserCommands
su:switchanormaluserintoarootsuperuserloginname:showstheloginnameexit:exittheshell.whoami:showsthecurrentusernamehostname:showsthecurrenthostnamesudo: allowsauserwithproperpermissions to execute a commandas anotheruser, such as the superuser su: switchanormaluser intoa root superuserExample:user2014@user-linux:~$su–l(su:switchanormaluserintoarootsuperuser.–l:enterrootpasswordandlogin.Note:Afterloginasasuperuser,the$willbecome#.)loginname:showstheloginnameExample:root@user-linux:~#loginname(loginname:showstheloginname,theoutputis“root”.Note:Afterloginasasuperuser,the$becomes#.)exit:exittheshellExample:root@user-linux:~#exit (exit:exit theshell. Inhere:exit thesuperusermode,andenterthenormalusermode.Note:Afterexitsuperuser,the#willbecome$.)whoami:showsthecurrentusernameExample:user2014@user-linux:~$whoami(whoami: shows the current user name, the output is “user2014”) hostname:showsthecurrenthostnameExample:user2014@user-linux:~$hostname(hostname: shows the current host name, the output is “user-linux”) sudo:allows a user with proper permissions to execute a command as anotheruser,suchasthesuperuserExample:root>sudo-uandylshomemydir(listthecontentsofthe homemydir directoryasuserandy.-u:specifyauser)root>sudo–v
(-v:refreshtheauthenticationtimeout,thenextsudocommandwillnotrequireapassword.)root>sudo-k(-k:expiretheauthenticationtimeout,thenextsudocommandwillrequireapassword.)Summary:su:switchanormaluserintoarootsuperuserloginname:showstheloginnameexit:exittheshell.whoami:showsthecurrentusernamehostname:showsthecurrenthostnamesudo: allowsauserwithproperpermissions to execute a commandas anotheruser,suchasthesuperuser
Chapter4NavigatingAtCommands
pwd:printworkingdirectory.cddir:changedirectory.cd~changedirectorytohomedirectory.cd..changedirectorytoaparentaldirectory.type:determineacommandtype.pwd:printworkingdirectory.Example:user> pwd(pwd:printworkingdirectory,theoutputisyourcurrentworking directory.) cd dir: change directoryExample: user> cdmydir (cd:changedirectorytomydir,theoutputismydir.)cd~changedirectorytohomedirectory.
Example:user>cd ~(cd~ change directory to home directory, the output is home directory.) cd..changedirectorytoaparentaldirectory.Example:
user>cd ..(cd..changedirectorytoaparentaldirectory,theoutputisaparentaldirectory.)type:determineacommandtypeExample:user>typepwd(output:pwdisashellbuiltin.)Summary:pwd:printworkingdirectory.cd:changedirectory.cd~changedirectorytohomedirectory.cd..changedirectorytoaparentaldirectory.type:determineacommandtype.
Chapter5FileOperationCommands
cp:copyafilemv:moveafilemv:renameafilerm:removeafilerm–ri:removeanon-emptydirectoryvi:openvieditorandeditafilefind:lookforafilewc:showwordcountofafilefile:estimatethetypeofafileln:createalinkbetweentwofilesln-s:createasymboliclinktoafilereadlink:showthetargetofasymboliclinklpr:sentafiletoprinterlpq:displaytheprintqueue.cp:copyafileExample:user>cpmyfile/dir1(cp:copymyfileto/dir1directory.)mv:moveafileExample:user>mvmyfile/dir2(mv:movemyfiletodir2directory.)mv:renameafileExample:user>mvmyfile1myfile2(mv:renamemyfiel1asmyfile2.)rm:removeafileExample:user>rmmyfile(rm:removemyfile.)rm–ri:removeanon-emptydirectoryExample:user>rm–riNonEmptyDir(rm:removeadirectorynamedNonEmptyDir.-ri: removeadirectorycontainingcontents.)vi:openvieditorandedita file
Example:user>vimyfile.txt(vi:openvieditorandeditmyfile.txt.)find:lookforafileExample:user>finddirectory–typef–namemyfile.txt-print(find:lookforafile.-typef:specifyafile-name:specifyafilename-print:print)wc:showwordcountofafileExample:user>wcmyfile.txt(wc:showwordcountofmyfile.txt.)file:estimatethetypeofafileExample:user>filemyfile.txt(file:estimatethetypeofmyfile.txt.)ln:createalinktoafileExample:user>lndir1/file1.txtdir2/file2.txt(ln:createalinkbetweenfile1andfile2)ln-s:createasymboliclinkbetweentwofilesExample:user>ln–sdir1/file1.txtdir2/file2.txt(ln-s:createasymboliclinkbetweenfile1and file2) (-s: a symbolic linkallowsagiven file to appear inmanyplacesorundermanynamesatonce.Forinstance,symboliclinkscanlinktodirectories.)readlink:showthetargetofasymboliclinkExample:user> readlink dir2/file2.txt (the output : dir1/file1.txt) lpr: sent a file toprinterExample:user>lprmyfile.txt(lpr:sentmyfile.txttoprinter.)lpq:displaytheprintqueue.Example:user>lpq(lpq:displaytheprintqueue.)Summary:cp:copyafilemv:moveafilemv:renameafilerm:removeafilerm–ri:removeanon-emptydirectoryvi:openvieditorandeditafilefind:lookforafilewc:showwordcountofafilefile:estimatethetypeofafileln:createalinkbetweentwofilesln-s:createa
symboliclinktoafilereadlink:showthetargetofasymboliclinklpr:sentafiletoprinterlpq:displaytheprintqueue.
Chapter6ViewingFileCommands
cat:showcontentsofafilecat|less:displayafilecontentspagebypagecat|more:displayafilecontentsscreenbyscreenhead:showthefrontpartcontentsofafile tail:showthe lastpartcontentsofafileaspell:spellingcheckforafilecut:showthespecifiedcolumnofatextfilepaste:mergetwofilescontentsanddisplaysort:showlinesoftextsortedalphabeticallystat:displaytheattributesofafileordirectorywc:displaywordcountinafilefile:testthefiletypetouch:createafileorchangefiletimestampnl:shownumbersforeachlineofafilevi:editorcreateatextfilewithvieditortr:transformtextinafiletee:printstandardoutput,writetoafilecat:showcontentsofafileExample:user>catmyfile.txt(cat:showcontentsofmyfile.txt.)cat|less:displayafilecontentspagebypageExample:user>catmyfile.txt|less(cat:showcontentsofmyfile.txt.|:redirecttheoutputtoanothercommandless:displaymyfile.txtcontentspagebypage)cat|more:displayafilecontentsscreenbyscreenExample:user>catmyfile.txt|more(cat:showcontentsofmyfile.txt.| : redirect the output to another command more: display myfile.txt contentsscreenbyscreen)head:showthefrontpartcontentsofafileExample:user>headmyfile.txt(head: show the front part contents of myfile.txt.) tail: show the last partcontentsofafileExample:user>tailmyfile.txt(tail:showthelastpartcontentsofmyfile.txt.)aspell:spellingcheckforafileExample:user>aspell–cmyfile.txt(aspell:spellingcheckformyfile.txt.-c:check)
cut:showthespecifiedcolumnofatextfileExample:user>cut–f2myfile.txt(cut:showthespecifiedcolumnofmyfile.txt.-f2:specifythesecondcolumn)paste:mergetwofilescontentsanddisplayExample:user>pastemyfile1.txtmyfile2.txt(paste:mergetwofilescontentsanddisplay)sort:showlinesoftextsortedalphabeticallyExample:user>sortmyfile.txt(sort:showlinesoftextsortedalphabetically.)stat:displaytheattributesofafileordirectoryExample:root>statmyfile.txt(stat:showfilename,modifydate,changetimeetc.)wc:displaywordcountinafileExample:root>wcmyfile.txt(wc:showthenumberoflines,words,bytesinafile)file:testthefiletypeExample:root>filemyfile.txt(output:myfile.txtASCIItext)touch:createafileorchangefiletimestampExample:root>touchmyfile.txt(touch:createafilenamedmyfile.txt)nl:shownumbersforeachlineofafileExample:root>nlmyfile.txt(output:023sldslwflflfgjo4ijggj4jf9ej024wzwgtjletjgeg4t4y025sjflewgjlgnu4gjgu675hdk9fhfmj6ju026jf5hjdfjtjfjd8gj1nfj,nuigrr?rit……)vi:editorcreateatextfilewithvieditorExample:root>vimyfile.txt(vi:openmyfile.txtwithvieditor)tr:transformtextinafileExample:
root>echoapple|tr“apple”“banana”(output:banana)tee:printstandardoutput,writetoafileExample:Root>sortfile1.txt|teefile2.txt(sortfile1.txtandwritetofile2.txt)Summarycat:showcontentsofafilecat|less:displayafilecontentspagebypagecat|more:displayafilecontentsscreenbyscreenhead:showthefrontpartcontentsofafile tail:showthe lastpartcontentsofafileaspell:spellingcheckforafilecut:showthespecifiedcolumnofatextfilepaste:mergetwofilescontentsanddisplaysort:showlinesoftextsortedalphabeticallystat:displaytheattributesofafileordirectorywc:displaywordcountinafilefile:testthefiletypetouch:createafileorchangefiletimestampnl:shownumbersforeachlineofafilevi:editorcreateatextfilewithvieditortr:transformtextinafiletee:printstandardoutput,writetoafile
Chapter7ComparingFileCommands
diff:showdifferencesbetweentwofilescmp: compare two files byte by byte comm: compare two files line by linemd5sum:createamd5checksumnumbercksum:createacrcnumberdiff:showdifferencesbetweentwofilesExample:user> diff myfile1.txt myfile2.txt (diff: show differences between two files.)cmp:comparetwofilesbytebybyteExample:user> cmp myfile1.txt myfile2.txt (cmp: compare two files byte by byte.)comm:comparetwofileslinebylineExample:user> commmyfile1.txt myfile2.txt (comm: compare two files line by line.)md5sum:createamd5checksumnumberExample:user>md5summyfile1.txt(output: f7tkgu5orj1fjt8kelc2os95nd57jf8r myfile1.txt.) cksum: create a crcnumberExample:user>chsummyfile2.txt(output:465879104819myfile2.txt.)Summarydiff: showdifferences between two files cmp: compare two files byte by bytecomm:comparetwofileslinebylinemd5sum:createamd5checksumnumbercksum:createacrcnumber
Chapter8MatchingTextCommands
grep:showalllinesthatcontainaspecifiedstringegrep:showalllinesthatcontainaspecifiedstringuniq:showuniquelinesinafilefind:locateafileinspecifieddirectorylook:showwordsmatchingagivenprefixgrep:showalllinesthatcontainaspecifiedstringExample:user>grepgoodmyfile.txt(grep: show all lines that contain “good” string.) egrep: show all lines thatcontainaspecifiedstringExample:user>egrepexcellentmyfile.txt(egrep:showalllinesthatcontain“excellent”string.)uniq:showuniquelinesinafileExample:user>uniqmyfile.txt(uniq:showuniquelinesinmyfile.txt.)find:locateafileinspecifieddirectoryExample:user>find/mydir–typefmyfile.txt-print(find:locateafileinadirectory.-typef:specifyafile-print:print)look:showwordsmatchingagivenprefixExample:User>lookab(output:aba,abb,abc,abd…)Summarygrep: show all lines that contain a specified string egrep: show all lines thatcontainaspecifiedstringuniq:showuniquelinesinafilefind: locate a file in specified directory look: show words matching a givenprefix
Chapter9DirectoryCommands
mkdir:makeanewdirectoryrmdir: remove a emptydirectorybasename:display the last part of a file pathdirname:showthedirectorypathonlymkdir:makeanewdirectoryExample:user>mkdirmydir(mkdir:makeanewdirectory)rmdir:removeaemptydirectoryExample:user>rmdirmydir(rmdir: remove a empty directory)basename: display the last part of a filepathExample:user>basenamehomefoo/usr/file.txt(output:file.txt)dirname:showthedirectorypathonlyExample:User>dirnamefoobar/baz/myfile.txt(output:foobar/baz)Summarymkdir:makeanewdirectoryrmdir:removeaemptydirectorybasename:displaythelastpartofafilepathdirname:showthedirectorypathonly
Chapter10Un/CompressCommands
zip:compressafiletozipformatunzip: uncompress a file from zip format gzip: compress files to gzip formatgunzip:uncompressfilesfromgzipformatbzip2:compressfiles tobz2formatbunzip2:uncompressfilesfrombz2formatzip:compressafiletozipformatExample:user>zipmyfile.txt(zip: compress myfile.txt to zip format.) unzip: uncompress a file from zipformatExample:user>unzipmyfile.zip(unzip:uncompressmyfile.zip.)gzip:compressfilestogzipformatExample:user>gzipmyfile.txt(gzip: compress a file to gzip format) gunzip: uncompress a file from gzipformatExample:user>gzipmyfile.txt.gz(gunzip: uncompress myfile.txt.gz) bzip2: compress files to bz2 formatExample:user>bzip2myfile.txt.(bzip2: compressmyfile to bz2 format)bunzip2: uncompress files frombz2formatExample:user>bunzip2myfile.txt.bz2(bunzip2:uncompressmyfilefrombz2format)Summaryzip:compressafiletozipformatunzip:uncompressafilefromzipformatgzip:compressfilestogzipformatgunzip:uncompressfilesfromgzipformatbzip2:compressfilestobz2formatbunzip2:uncompressfilesfrombz2format
Chapter11ProcessesCommands
ps:showthecurrentprocessesofuserkill:killaprocessbyprocessidw:showallcurrentworkingprocess.df:showdiskusageoffilesystemuptime:showsystemuptimetop:viewthetopactiveprocessoraspecifiedprocess.ps:showthecurrentprocessesofuserExample:root>ps–uusername(ps:showthecurrentprocessesofauser.-u:specifyausername)kill:killaprocessbyprocessidExample:root>kill6270(kill:killaprocessbyprocessid6270:aprocessid.)w:showallcurrentworkingprocessExample:root>w-s(w:showallcurrentworkingprocess.-s:showsummaryofprocess.)df:showdiskusageoffilesystemExample:root>df-h(df:showdiskusageoffilesystem.-h: make the output more understandable) uptime: show system uptimeExample:root>uptime(uptime: show systemuptime.) top: view the topactive or specifiedprocessExample:root>top-ppid(top:showaprocessbypid)(-p:displayspecifiedprocessbypid)(pid:processid)Summaryps:showthecurrentprocessesofuserkill:killaprocessbyprocessidw:show
allcurrentworkingprocess.df:showdiskusageoffilesystemuptime:showsystemuptimetop:viewthetopactiveprocessoraspecifiedprocess.
Chapter12AccountCommands
useradd:addanewuseraccountusermod: modify an existing user account userdel: delete an existing useraccount passwd: set a user account password chfn: change personal fingerinformation finger: display personal user finger information useradd: add anewuseraccountExample:root>useraddusername(useradd:addanewuseraccount.)usermod:modifyanexistinguseraccountExample:root>usermod–loldnamenewname(usermod:modifyanexistinguseraccount.-l:modifyloginname.)userdel:deleteanexistinguseraccountExample:root>userdelusername(userdel:deleteanexistinguseraccount.)passwd:setauseraccountpasswordExample:root>passwdusername(passwd:setauseraccountpasswordforauser.)chfn:changepersonalfingerinformationExample:root>chfnusername(chfn:changefingerinformationforauser).finger:displaypersonaluserfingerinformationExample:root>fingerusername(finger:listtheuser'sloginname,email,domainname,time.etc.)Summaryuseradd: add a new user account usermod: modify an existing user accountuserdel: delete an existing user account passwd: set a user account passwordchfn: change personal finger information finger: display personal user fingerinformation
Chapter13GroupsCommands
groups:showthegroupmembershipgroupadd:createanewgroupgroupmod:modifyanexistinggroupgroupdel:deleteanexistinggroupgroups:showthegroupmembershipExample:root>groupsusername(groups:showthegroupmembershipofauser.)groupadd:createanewgroupExample:root>groupaddnewgroup(groupadd: create a new group named newgroup.) groupmod: modify anexistinggroupExample:root>groupmodnewgroup(groupmod:modify an existing group named newgroup.)groupdel: delete anexistinggroupExample:root>groupdelnewgroup(groupdel:deleteanexistinggroupnamednewgroup.)Summarygroups:showthegroupmembershipgroupadd:createanewgroupgroupmod:modifyanexistinggroupgroupdel:deleteanexistinggroup
Chapter14PermissionCommands
chmod:changemodeofaccesspermissionschgrp:changegroupmembershipchown:changeownershipofafileordirectory(Accesspermissionindetailwillbeinlaterchapter.)chmod:changemodeofaccesspermissionsExample:root>chmod752myfile1.txt(chmod:changemodeofaccesspermissionformyfile1.txt.7: set user permission with read, write, execute 5: set group permission withread,execute2:setotherspermissionwithwriteonly.)chmod:changemodeofaccesspermissionsExample:root>chmodg+wmyfile.txt(g+w: give write permission to member of the file’s group) chgrp: changegroupmembershipExample:root>chgrpgroupnamemyfile2.txt(chgrp:changegroupmembershipofmyfile2.txt)chown:changeownershipofafileordirectoryExample:root>chownusernamemyfile3.txt(chown:changeownershipofmyfile3)Example:root>chowngroupnameuserdir(chown:changeownershipofdir.)Summary:chmod:changemodeofaccesspermissionschgrp:changegroupmembershipchown:changeownershipofafileordirectory(Accesspermissionindetailwillbeinlaterchapter.)
Chapter15RunningJobCommands
job:displaythestatusofalljobsfg: run a suspended job in foreground bg: run a suspended job in backgroundkill:killajobbynumberoraprocessbypidat:scheduleajobrunataspecifiedtimeatq:displaythescheduledjobsatrm:removeascheduledjobps:showcurrentprocessstatusw:showwhologgedonandwhatdoinguptime:show how long the system has been running top: view the top active processcrontab:createajobtorunatspecifiedtimejob:displaythestatusofalljobsExample:root>jobs(job: display the status of all jobs.) fg: run a suspended job in foregroundExample:root>fg%2(fg%2: run a suspended job%2 in foreground.)bg: runa suspended job inbackgroundExample:root>bg%3(bg%3:runasuspendedjob%3inbackground.)kill:killajobbynumberoraprocessbypidExample:root>kill%4(kill%4: kill a running job%4) at: schedule a job run at a specified timeExample:root>at9:30pm(at9:30:setaschedulejobat9:30.)atq:displaythescheduledjobsExample:root>atq(atq:displayallscheduledjobs)atrm:removeascheduledjobExample:root>atrm25(atrm 25: remove a scheduled job 25.) ps: show current process statusExample:root>ps-f(ps-f: show full information of current process.) ps: show current processstatusExample:root>ps-uusername(ps-u:showauser’scurrentprocess.)w:showwhologgedonandwhatdoingExample:
root>w-susername(-s:showsummaryinformationofauser.)uptime:showhowlongthesystemrunningExample:root>uptime(uptime:showsystemuptime.)top:viewthetopactiveorspecifiedprocessExample:root>top(top:displayallprocessesrunningonthesystem)crontab:createajobtorunatspecifiedtimeExample:root>crontab-e(-e:editthecrontabfile,addacrontabjobtothetable)Summaryjob:displaythestatusofalljobsfg:runasuspendedjobinforegroundbg:runasuspended job inbackgroundkill:killa jobbynumberoraprocessbypidat:schedule a job run at a specified time atq: display the scheduled jobs atrm:removeascheduledjobps:showcurrentprocessstatusw:showwhologgedonandwhatdoinguptime:show how long the system has been running top: view the top active processcrontab:createajobtorunatspecifiedtime
Chapter16Backup/RestoreCommands
cpio:outputorinputanarchivecpiofiletar:create,view,extractarchivedtarfilecpio-o:outputanarchivecpiofileExample:root>cpio-o>directory.cpio(-o:backuptoaarchivecpiofile)cpio-i:inputanarchivecpiofileExample:root>cpio-i<directory.cpio(-i:restorefromaarchivecpiofile)tar-xf:extractanarchivedtarfileExample:root>tar-xfarchive.tar(-xf:extractanarchivetarfile)tar-cf:createanarchivedtarfileExample:root>tar-cfarchive.tar(-cf:createanarchivetarfile)
Summarycpio:outputor input anarchivecpio file tar: create,view,extract archived tarfile
Chapter17Date&TimeCommands
date:displaytdateandtimecal:displayacalendarofmonthdate:displaydateandtimeExample:root>date(date: display the current date and time.)date “+%A”:display currentdayExample:root>date“+%A”(output:Sunday)date“+%D”:displaycurrentdateExample:root>date“+%D”(output:08/10/14)date“+%T”:displaycurrenttimeExample:root>date“+%T”(output:11:30:28)cal:displayacalendarofmonthExample:root>cal(cal:displayamonthcalendar.)Summarydate:displaydateandtimecal:displayacalendarofmonth
Chapter18NetworkingCommands
host:displayremotehostnameandIPifconfig:displaylocalnetworkconfigurationping:sendpacketstotestifremotehostreachablessh:securelyconnect toaremotecomputerftp:files transferby“FileTransferProtocol”mesg:enableordisablemessagingwrite:writeamessagestootherusersopen:connecttoanftpservermail:sendandreceivemailslocallyandglobally.dhclient:providesameansforconfiguringoneormorenetworkinterfacesnslookup:queryinternetnameserversinteractivelyforIPinformation.host:displayremotehostnameandIPExample:root>hostwww.yahoo.com(host: display remote hostname and IP.) ifconfig: display local networkconfigurationExample:root>ifconfig(ifconfig: display local network configuration) ping: send packets to test ifremotehostreachableExample:root>ping-c3yahoo.com(ping:sendpacketstotestifyahoohostisreachable.-c3:specifythenumberofpings)ssh:securelyconnecttoaremotecomputerExample:root>sshray@myusername.com(ssh:securelylogintoaremotecomputer)ftp:filestransferby“FileTransferProtocol”Example:root> ftp ftpexample.myexample.com (ftp: connecting toftpexample.myexample.comandtransferfilesremotely)mesg:showmessagingExample:root>mesg(mesg:showcurrentstatusofmessaging)mesgy:enablemessagingExample:
root>mesgy(mesgy:permitmessaging)mesgn:disablemessagingExample:root>mesgnmesgn:denymessaging)write:writeamessagestootherusersExample:root>writeken(writeamessagetoken)open:connecttoanftpserverExample:root>openftp.myexamples.com(open: connect to ftp.myexamples.com)mail: send and receivemails locallyandglobally.Example:root> mail username@myexamples.com (mail: send a mail tousername@myexamples.com)dhclient:providesameansforconfiguringoneormorenetworkinterfaces.Example:root>dhclienteth0(renew the dynamically assigned IP address of a primary Ethernet device.)nslookup:queryinternetnameserversinteractivelyforIPinformation.Example:root>nslookupmyexample.com (return an IP address,e.g. 75,126,166, 2XX )(nslookup:manuallyqueryDNSservers.TheDNS(DomainNameSystem)protocolallowsyoutogetanIPaddressforagiven host name from a name server. This process is called resolving.)Summaryhost:displayremotehostnameandIPifconfig:displaylocalnetworkconfigurationping:sendpacketstotestifremotehostreachablessh:securelyconnect toaremotecomputerftp:files transferby“FileTransferProtocol”mesg:enableordisablemessagingwrite:writeamessagestootherusersopen:connecttoanftpserver
mail:sendandreceivemailslocallyandglobally.dhclient:providesameansforconfiguringoneormorenetworkinterfacesnslookup:queryinternetnameserversinteractivelyforIPinformation.
Chapter19ScriptingCommands
echo:displaytext.expr:performmathcalculation#!/bin/bash:put in the first lineofabashshellscriptsfile.echo:displaytext.Example:root>STR=”HelloWorld!”root>echo$STR(echo:displaytext.Theoutputis“HelloWorld!”)echo-e:displaytextusingescapesequences.Example:root>STR=”HelloWorld!”root>echo–e“\n$STR\n”(echo-e:displaytextusing\n.\nmeansaddanewline.)Theoutputis“HelloWorld!”expr:performmathcalculationExample:user>expr20+80(Theoutputis“100”)Example:user>expr21/7(Theoutputis“3”)Example:user>expr9“>”6(Theoutputis“1”,the1meanstrue)Example:user>expr9“<”6(Theoutputis“0”,theomeansfalse)#!/bin/bash:putinthefirstlineofbash
shellscripts.Example:#!/bin/bashIf…then…else…fi(#!/bin/bash:alwaysputinthefirstlineofbashshellscripts)Summaryecho:displaytext.expr:performmathcalculation#!/bin/bash:alwaysputinthefirstlineofabashshellscripts
Chapter20SystemCommands
df:showdiskusageoffilesystemmount: make a device available to file system umount: make a deviceunavailabletofilesystemfsck:checkandrepairthefilesysteminitn:switchthesystem to run level nwho -r: show the current run level free: show free diskspacedu: showdisk usage of a file or directory export: set an environment variableprintenv: list environment variable names and values unset: remove theenvironmentvariableclear:clearthescreenexit:exittheshellorlogout.shutdown–h+n:thesystemisgoingdowninnminutes!df:showdiskusageoffilesystemExample:root>df-h(df:showdiskusageoffilesystem.-h:makeoutputunderstandable)mount:makeadeviceavailabletofilesystemExample:root>mount/cdrom(mount: make a cd-rom available to file system.) umount: make a deviceunavailabletofilesystemExample:root>umount/dev/hda1(umount:makehda1unavailabletofilesystem.hda1:aharddrivepartition)fsck:checkandrepairthefilesystemExample:root>fsck(fsck:checkandrepairthefilesystem.)initn:switchthesystemtorunlevelnExample:root@user-linux:~#init5(init5: switch the system to run level5)who -r: show thecurrentrun levelExample:root@user-linux:~#who-r(who-r:showthecurrentrunlevel.)free:showfreediskspace
Example:root@user-linux:~#free-m(free:showfreediskspace-m:showfreediskspaceinMBunit)du:showdiskusageofafileordirectoryExample:root@user-linux:~#du–bmyfile.txt(du:showdiskusageofafileordirectory.-b:countthenumberofbytesitoccupies.)export:setanenvironmentvariableExample:root@user-linux:~#exportnewvar=8(echo$newvar.Theoutputis8)printenv:listenvironmentvariablenamesandvaluesExample:root@user-linux:~#printenv(printenv: list environment variable names and values) unset: remove theenvironmentvariableExample:root@user-linux:~#unsetvar(unsetvar:removetheenvironmentvariablevar.)clear:clearthescreenExample:user>clear(clear:clearthescreen.)exit:exittheshellorlogout.Example:user>exit(exit:exittheshellorlogout.)shutdown–h+n:thesystemisgoingdowninnminutes!Example:root@user-linux:~#shutdown–h+5(shutdown–h+5:thesystemisgoingdownin5minutes!)(-h:haltthesystem+n:afternseconds)
Summary:df:showdiskusageoffilesystemmount:makeadeviceavailabletofilesystem
umount:makeadeviceunavailabletofilesystemfsck:checkandrepairthefilesysteminitn:switchthesystemtorunlevelnwho-r:showthecurrentrunlevelfree:showfreediskspacedu: showdisk usage of a file or directory export: set an environment variableprintenv: list environment variable names and values unset: remove theenvironmentvariableclear:clearthescreenexit:exittheshellorlogout.shutdown–h+n:thesystemisgoingdowninnminutes!
Chapter21HelpingCommands
Commands Operations&Examplesman displaymanualforacommande.g.man
nice(showthemanualfornicecommand)
info displayinformationforacommande.g.infochmod(showinformationaboutchmodcmd)
whatis displayadescriptionofwhatacmdise.g.whatisifconfig(showadescriptionofwhatifconfigis)
help displayhelpexplanationofacmde.g.helpcd(showhelpexplanationofcdcmd)
apropos searchmanualpagesforakeyworde.g.aproposdownload(showmanualentrieswith“download”)
--help -helpoptiongetshelpforacommande.g.wget--help(gethelpforwgetcmd)
Note:Ifyouare familiarwithhelpingcommands,youwillknowabout thecompleteLinuxcommandsandtheirusages.
Chapter22SkillofCommands
MakeuseofTabkeytoautocompleteLinuxofferssomanydifferent commands thatwe easily to get lost and to forget one. Personally, ithappensveryregularly,butthisisfortunatelynotadrama.Indeed,Linuxoffersavarietyofwaystofindacommandthatyoumissed.Thefirst"trick"toknowwhatistoautocompletecontrol.Example:Forthedatecommand:you'realittleheadacheandyoudonotknowhowitiswritten. By cons, you are sure the first or second letters of the command are“da”.Just type "da" in the console, then double-tap the Tab on the left of yourkeyboardBydouble tappingTab, you asked the computer a list of commandsthat begin with "da". They said you "dash" and "date". So there are twocommandsthatstartwith"da",andyoujustfindtheoneyouarelookingfor,thatistosay"date".Verynice,thecomputerhasrewrittenthepromptbelowandthebeginningofthecommandyoutyped.Youonlyhavetocompletewiththeletters"you"missingand hitting Enter and it will be good. :-) Evenmore fun, if there is only oneresultforyoursearch,thecomputerwillcompletewithmissinglettersandyouonlyhavetopressEnter!Example:Ifyouwanttotype“chsh”commandandyouarenotsurethespelling,youcanonly type “ch” in the console and press two times on Tab. The command iscompletedmagically.Itwilldisplay“chfn,chsh”,thenyoucanchoose“chfn”.Commaaaandestoo!
The commandhistoryWe often need to find a command that wastypedtherefiveminutes(orevenfiveseconds).Sometimesitisbecausewehaveforgottenthecommand,butit'softenbecauseyoulikemeyoureallytoolazytorewriteourselvestheentirecommand.Thisshortcut isgold:press theUparrowkey;youwill see the lastcommandyoutyped.If you press again the directional arrow Top, you will see the penultimatecommand,thenthesecond-to-last,etc.
IfyoupresstheDownarrowkey,youwillreturntothemostrecentcommands.ThusIcansuccessivelyfindthecommandsIjusttypeinreversecommand:ls--all;ls-a,ls;Date;Etc.Ifyouwantto"go"veryfarbackintothehistoryofyourcommands,noneedtotypeahundredtimesonthedirectionalarrowToplikemadmen.There is the history command that reminds you of the command history:Example:Press theUparrowkey; youwill see the last command you typed.Then thescreenwilldisplay:Date152 ls ls ls153154155--all -a156157historyYouwill notice that the controls arenumbered: thus,wecanknow thatdate is the152ndcommandItypedintotheterminal,thatthreelsarethe153rd,154rthand156th command. The above command you typed will always be history, ofcourse.
Ctrl+R:findahistorycommandIncasethedirectionalarrowTopandhistorycommanddoesnotsufficetofindanoldcommandyoutyped,thereisasuperusefulshortcut:Ctrl+R.whichcanhelpyoufindoutthehistorycommand you have just used. So Press Ctrl+R keys simultaneously andcomputerwillswitch"lookingforatypedcommand"("R"asresearch).Thereyoucantypeanysequenceoflettersthatcorrespondstoanoldcommand.Example:Ifyouwanttolookforacommandwith“all”youhavepreviouslyused,pleasepressCtrl+Randtype"all".Then,Linuxwillfindoutls--allcontainingjusttheword"all."YoujusthavetohitEntertorunthecommand!:-)Ifthisisnotthecommand you are looking for, again press Ctrl + R to move up the list ofcommandscontaining"all".Itmaylookstupidonadrivelikethat,butsomeareverylonganditisapleasurenottohavetorewritethemagain!
UsingWildcardsYoucanusewildcardswithalotofLinuxcommands.Awildcardisasymbolorsymbolsthatindicatingothercharacters.TherethreekindsofwildcardsinLinuxcommand:?Aquestionmark(?)indicatesasinglecharacter.For instance: b??k matches bank, beak, back, bilk, or any other four-letter
filenamethatbeginswithbandendswithk.* An asterisk (*) indicates any character or set of characters, including nocharacterormanycharacters.Forinstance:b*kmatchesbk,bkk,bark,break,backtrack.[]Charactersenclosedinsquarebrackets([])usuallyindicatesanycharacterintheset.Butpleasenotetheyarecase-sensitive.For instance: b[a-z]kmatches bak, bbk, bck, bzk, but notmatches bAk, bBk,bCk,bZk,becauseofcase-sensitive.WildcardsareactuallyimplementedintheLinuxcommands.Example:user2014@user-linux:~$ ls b??k (The wildcard b??k matches five files incurrentdirectory.Theoutputis“bankbeakbackbilkbark”)Example:user2014@user-linux:~$ ls a*d (The wildcard a*d matches some files incurrentdirectory.Theoutputis“adaddacidabroadabounded abedaid”)Example:user2014@user-linux:~$lsse[a-e](Thewildcardse[a-e]matchesfivefilesincurrentdirectory.Theoutputis“seasebsecsedsee”)AboutRunLevelsWhatisaRunLevels?Thetermrunlevelsreferstoamodeofoperationinoneofthecomputeroperatingsystemsthat implement Linux System V-style initialization. Usually, seven run levelsexist,numberedfromzerotosix;Onlyone"runlevel"isexecutedonbootup-run levels are not executed sequentially, i.e. either run level 2OR 3OR 4 isexecuted,not2then3then4."runlevels"definesthestateofthemachineafterboot.Differentrunlevelsaretypicallyassignedto:0.halt-thesystemisintheprocessofshuttingdown.1.single-usermode2.multi-usermodewithoutnetworkservicesstarted3.multi-user mode with network services started 4.system shutdown 6.system rebootExample:root@user-linux:~#init3(init3:switchthesystemtorunlevel3)Summary:Tabkeycanautocompleteamissingworkcommand.Up arrow key can view the history commandsDown arrow key can return tomostrecentcommandsCtrl+Rcanfindoutahistorycommandbyakeyword.?Aquestionmark(?)indicatesasinglecharacter.* An asterisk (*) indicates any character or set of characters, including nocharacterormanycharacters.[]Charactersenclosedinsquarebrackets([])usuallyindicatesanycharacterin
theset.Butpleasenotetheyarecase-sensitive.RunLevelnumberdescribersthelevelofservicesthathavebeeninitializedandarerunning.
Chapter23AccessPermissions
Whatisrwx?Afterusingls–ltoviewafile’saccesspermissions,youcanseesomethinglikethis:rwx…..……
Explanation: rwx signify the access permissionswhich can be described by anumber from1 to7.Really?Yes, thenumbers from1 to7 indicate theaccesspermissions.rstandsforreadpermissions,valueis4.wstandsforwritepermissions,valueis2.xstandsforexecutepermissions,valueis1.Vice versa:4means readpermissions (r)2meanswritepermissions (w)1meansexecutepermissions(x)Example:Ifrwxvalueis4,thenyoucanfigureoutitspermissionisreadonly.Ifrwxvalueis2,thenyoufigureoutitspermissioniswriteonly.Ifrwxvalueis1,thenyoufigureoutitspermissionisexecuteonly.Thenumbersfrom1to7indicatethevariousaccesspermissions:7meanspermissionswithread,write,execute(7=4+2+1)6meanspermissionswithread,write(6=4+2)5meanspermissionswithread,execute(5=4+1)4meanspermissionswithreadonly(4=4+0)3meanspermissionwithwrite,execute(3=2+1)2meanspermissionwithwriteonly(2=2+0)1meanspermissionwithexecuteonly(1=1+0)Example:Ifrwxvalueis7,thenyoucanfigureoutitspermissionisread,writeandexecute.Ifrwxvalueis6,thenyoucanfigureoutitspermissionisreadandwrite.Ifrwxvalueis3,thenyoucanfigureoutitspermissioniswriteandexecute.
Whatarerwxrwxrwx?Access permissions for a file are divided in to three: user permissions, grouppermissions, others permissions, So, when you use ls –l to view the access
permission,youwillfindthreerwxlooklikethis:rwxrwxrwx……Explanation:The1st rwxmeansuserpermissions,The2nd rwxmeansgrouppermissions,The3thrwxmeansotherspermissions.Example: If the 1st rwx is 7, it means user permissions with read, write,execute.Ifthe2ndrwxis3,itmeansgrouppermissionswithwriteandexecute.Ifthe3thrwxis6,itmeansotherspermissionswithreadandwrite.Fromaboveyoucanunderstandthe1strwx,2ndrwxand3thrwxrespectivelyindicateuserpermissions,grouppermissionsandotherspermissions.Example:752means:1strwxis7meaninguserpermissionswithread,write,execute.2ndrwxis5meaninggrouppermissionswithread,andexecute.3thrwxis2meaningotherspermissionswithwriteonlychmodisacommand,meaningchangethemodeofaccesspermissionsforafile.Example:chmod643myfile.txtExplanation:Changemyfile.txtpermissionsto643.1strwxis6meaninguserpermissionswithread,andwrite.2ndrwxis4meaninggrouppermissionswithreadonly.3thrwxis3meaningotherspermissionswithwrite,executeExample:chmod751myfile.txtExplanation:Changemyfile.txtpermissionsto751.1strwxis7,meaninguserpermissionswithr,w,x.2ndrwxis5meaninggrouppermissionswithr,x.3thrwxis1meaningotherspermissionswithxonly.Example:Chmodu+r(givestheuserareadpermission)Example:Chmodg-x(removeexecutepermissionfrommembersofthefile’sgroup)Example:Chmodo-w(removewritepermissionfromothers)Summary:4meansreadpermissions(r)2meanswritepermissions(w)1meansexecutepermissions(x)Thenumbersfrom1to7indicatethevariousaccesspermissions:7meanspermissionswithread,write,execute(7=4+2+1)6meanspermissionswithread,write(6=4+2)5meanspermissionswithread,execute(5=4+1)4meanspermissionswithreadonly(4=4+0)3meanspermissionwithwrite,execute(3=2+1)2meanspermissionwithwriteonly(2=2+0)1meanspermissionwith
executeonly(1=1+0)
Chapter24LinuxSymbols
Commands Operations&Examples< getinputfromafiletoacommand
e.g.cat<myfile.txt> sendoutputfromacommandtofile
e.g.cat>myfile.txt>> appendoutputtoafilee.g.cat
file1.txt>>file2.txt
|sendcmd1outputtocmd2inpute.g.ls-al/etc|less
;combinetwoormorecommandse.g.cd~;ls
\escapethespecialcharactere.g.echo-e“\nHello\tWorld!\n”
./runascriptinthecurrentdirectorye.g../script.sh
.. parentdirectorye.g.cd..
~homedirectorye.g.cd~
$variableprefixforvariablenameandvaluee.g.echo$var
$$showtherunningprocessesnumbere.g.echo$$
!! repeatthelastcommande.g.!!!string runrecentcmdthatbeginswithstring
e.g.!cat
Chapter25ShortcutKeys
CTRL+B movethecursorbackwardonlyone
character.CTRL+C canceltherunningcommandorkill
therunningprocess.CTRL+D logoutofthecurrentsession.similar
toexitcommand.CTRL+F movethecursorforwardonlyone
character.CTRL+H eraseonebackwardcharacter.similar
topressingbackspace.CTRL+P pastethepreviousline(s)toone
specifiedlocation.CTRL+R typetobringuprecentcommands,
returnalistofcommandsinhistoryCTRL+S stopalloutputonscreen.freezethe
shellasitlockstheterminaloutputCTRL+Q resumeallstoppedoutputonscreen,
continuetheterminaloutput.CTRL+U erasethecompletelinewherethe
cursorlocates.CTRL+W deletethelastrecentwordyouhave
justtypedin.CTRL+Z suspendarunningprocess.ifwantto
resume,usefgorbgcommands.
Chapter26RunLevelsTable
RunLevel
Description
0 Haltthesystem.Whenthisisthecurrentrunlevel,thesystemisintheprocessofshuttingdown.
1 Singleusermode.Onlysmallsetofkernelprocessesrunning.Almostallotherservicesdisabled.
2 Basicmultiusermode.Thisrunlevelstartsmostservices,butdoesnotenablenetworkconnectionservice.
3 Fullmultiusermode.Thisrunlevelstartsallservicesincludingnetworkconnection.butdoesnotstartXwindow
4 Userdefinedmode.Noconventionaldefinitionappliestorunlevel4.Itisfullyopentouserconfiguration.
5 FullmultiusermodewithXwindow.StartsallenabledserviceswithLinuxgraphicaldesktopenvironments.
6 Reboot.Whenthisisthecurrentrunlevel,thesystemisintheprocessofrebooting.
Chapter27TheViEditorCommands
Commands Operationsh,l,k,j cursormoveleft,right,up,downw,b cursormoveforward,backward0 gotothebeginningofline
$gototheendingofline
G gotothelastlineofthefileJ joincurrentlinewithnextlinez undolastcommand. repeatlastcommandZZ savefileandexiti insertbeforethecharacteratcursorI insertcharactertobeginningoflinea appendafterthecharacteratcursorA appendcharactertotheendingoflinec changeuntil…C changetoendoflined deleteuntil…D changetoendofliner replaceonecharacterR replacemorecharacterso openanewlinebelowO openanewlineaboveesc exitinsertmode,gotocmdmodex deletethecharacteratcursorX deletethecharacteratleftu undolastchange. redolastchangeU restoreline
m markpositionM middleofscreendw deletecurrentworddd deletecurrentlinecc changecurrentlinefx findxoncurrentlineFx findxonpreviousline/string searchstring,lookforwards?string searchstring,lookbackwards[n]G gotolinenumber“n”n searchforwardnextN searchbackwardnextp pasteline(s)belowcurrentlineP pasteline(s)abovecurrentlinet to…T backwardto…s substituteS substituteentirelineZZ writeandquit:e editfile:e! forgetchangeoffile:$ gotolastlineoffile:number gotolinenumber:w writeandsave:w! savewithread-onlyfile:wfilename savewithnewfilename:wq write,saveandquit:n gotonextfile:rew gotothefirstfile:q quitafterusing:wtosave:q! quitwithoutsaving:rfilename readfile,insertfileatcursorposition:!command runashellcommand:sh runatemporaryshell
Chapter28AllEssentialLinuxCommands
Note:cmdmeanscommandregexmeansregularexpression(*)meansthecommandrunbyrootuser
Commands Operations &Examples
a2p translateawktoperle.g.a2pmyfile.awk>myfile.pl(translatemyfile.awkintoplfile)
alias createanothernameforacommande.g.aliasp="pwd"(setpasaliasforpwd)
apropos viewthesearchedterminmanpagese.g.aproposfind(listentrieswith"find"inmanpage)
apropos-e viewsearchedterminmanpagese.g.apropos–enice(-e:showexactwordinmanpages)
apt-get install,removeorupdateapackagee.g.apt-getinstalllibc6(installlibc6package)
aspell checkandcorrectformisspellingse.g.aspell-ctest.txt(-c:checkspellingintest.txtfile)
at runajobatascheduletimee.g.at1AMFri(runthejobat1amFriday)
awk matchtextbyregularexpressione.g.awk'length($0)>88'text.txt(listonlylineslongerthan88
words)basename displaythelastpartofafilepath
e.g.basenamehomefoousrfile.txt(output:file.txt)
bc performacalculationbyacalculatore.g.bc8+9(output:17)
bg resumeastoppedjobinbackgrounde.g.bg%3(resume%3jobinbackground)
bunzip2 uncompressafilefromzipformate.g.bunzip2myfile.tar.bz2(uncompressmyfile.tar.bz2)
bzip2 compressafiletozipformate.g.bzip2myfile.dat(compressmyfile.dat)
cal displayamonthoryearcalendare.g.cal2014(display2014calendar)
cal-3 displayamonthoryearcalendare.g.cal-3(-3:display3months)
cat displaycontentsofoneofmorefilese.g.catfile1.txtfile2.txt(displaycontentsoffile1andfile2)
cat-n displaycontentsofoneofmorefilese.g.cat–nmyfile.txt(-n:specifynumberofoutputlines)
cd changedirectorye.g.cdhomeuser/mydir(changecurrentdirectorytomydir)
chattr setattributesforafilee.g.chattr+imyfile.txt(+imakethefileasread-only)
chfn changeuser’sfingerinformatione.g.chfn(changeallusersinformation)
chfn-f changeuser’sfingerinformatione.g.chfn–fFull-Name(-f:changefullname)
chgrp* changethegroupownershipe.g.chgrpgroupnameusrmyfile.txt(altergroupownershipofmyfile.txt)
chkconfig* viewandmodifyrunlevelfilee.g.chkconfig–list(-list:listservicesofrunlevel)
chmod changeaccesspermissione.g.chmod755filename(setfileaccesspermissionas755)
chown* changeownershipoffileordirectorye.g.chownusernamemyfile.txt(alterfileownershipofmyfile.txt)
chpasswd* changepasswordforusers.e.g.chpasswd(thenenterusername:password)
chsh* changeloginshellforausere.g.chsh-sbinbashray(-sspecifyloginshell)
cksum produceaCRCchecksumnumbere.g.cksumfile.txt(outputchecksumnumberoffile.txt)
clear clearthescreen.e.g.clear(cleartheshellwindow)
cmp comparetwofilestextbytebybytee.g.cmpfirst.txtsecond.txt(comparefirst.txtandsecond.txt)
collectl monitorthecurrentsystemstatuse.g.collectl(listcpu,sys,inter.etcinformation)
comm comparetwofilestextlinebylinee.g.commfirst.txtsecond.txt
(comparefirst.txtsecond.txt)cp copyfile(s)toanotherdirectory
e.g.cpmyfile.txt/mydir(copymyfile.txttomydir)
cp-p copyfile(s)toanotherdirectorye.g.cp–pmyfile.txt/mydir(-p:keeporiginalpermission)
cp-a copyfile(s)toanotherdirectorye.g.cp–amyfile.txt/mydir(-a:keeporiginalattributes)
cpio-o outputarchivedcpiofilee.g.cpio-o>directory.cpio(-o:backuptoanarchivecpiofile)
cpio-i inputarchivedcpiofilee.g.cpio-i<directory.cpio(-i:restorefromanarchivecpiofile)
crontab createajobtorunatspecifiedtimee.g.crontab(settorunjobsatregularintervals.)
crontab-e runarecurringjobataspecifiedtimee.g.crontab-e(-ealloweditthecrontabfile)
crontab-l runarecurringjobataspecifiedtimee.g.crontab-l(-l:liststhecrontabfiles)
crontab-r runarecurringjobataspecifiedtimee.g.crontab-r(-r:removethecrontabfile)
csplit splitafileintosomeseparatedfilese.g.csplitmyfile.txt”/part1/”“part2”(separatefilesnamedxx00,xx01)
cut-d showthespecifiedfieldofafilee.g.cut–d“:”myfile.txt(-d:specifyafielddelimiter“:”)
cut-c extractcontentsfromafilee.g.cut–c6myfile.txt
(-c6:thesixthcharacterofeachline)
cut-f extractcontentsfromafilee.g.cut–f3myfile.txt(-f3:specifyafieldnumberas3)
date showthedateandtimee.g.date(displaythecurrentdateandtime)
date-s setthedateandtimee.g.date-s"11/20/2014"(-ssetthedate)
dc openacommandlinedeskcalculatore.g.dc(“dc”meansdeskcalculator)
dd datadumptoconvertandcopyafilee.g.ddif=devsdaof=devsdb(copydatafromsdatosdb)
dmesg printoutallkernellogmessagese.g.dmesg>kmsg.txt(outputkernelmessagestokmsg.txt)
df displayfreediskspacee.g.df(displayfilesystemfreespace)
df-m displayfreediskspacee.g.df-m(-m:displaysizesinMb)
dhclient configurenetworkinterfacese.g.dhclienteth0(renewIPaddressofeth0)
diff showdifferencebetweentwofilese.g.difffirstfile.txtsecondfile.txt(displaydifferenceabovetwofiles)
diff3 showdifferenceamongthreefilese.g.diff3file1.txtfile2.txtfile3.txt(displaydifferenceabovethreefiles)
dig displaythedetailsofDNSserverse.g.digxvxaxx.com(listinformationaboutxvxaxx.com)
dir showdirectorycontentse.g.dir(displaycurrentdirectorycontents)
dircolors showcolorsettingsfor“ls”command.e.g.dircolors(displaydirectorycoloringofls)
dirname removethelastpartofafilepath.e.g.dirnamefoobar/baz/myfile.txt(output:foobar/baz)
du-s displaydiskusagee.g.du-s*.*(-slistfilessizeincurrentdirectory)
du-h displaydiskusagee.g.du-hmyfile.txt(-h:showhumanreadableunits)
dump-f makesbackupoffilesysteme.g.dump-f0filebk/mydir(-f:backup-0:dump-levelfilebk:dump-file)
echo displayinputonstandardoutpute.g.echo“HelloWorld!”(show“HelloWorld!”)
echo-e displaytextusingescapesequencee.g.echo–e“\nHelloWorld!”(-e:allowuse\ntoshowtext)
ed openacommand-linetexteditore.g.edmyfile.txt(openmyfile.txtwithtexteditor)
egrep searchfile(s)foraspecifiedregexe.g.egrep"new|string"myfile.txt(searchmyfile.txtfor“new|string”)
eject ejectthecdordvdtraye.g.ejectcdrom
(ejectcdromtray)eject-t ejectorclosethecdordvdtray
e.g.eject–tcdrom(-t:closeanopencdromtray)
emacs powerful,extensiblefileeditore.g.emacsfile.txt(launchemacsandopenfile.txt)
env show,settheenvironmentvariablese.g.env(listcurrentenvironmentvariables)
eval makeacommandfromitsargumentse.g.UPLS=”evalcd..;ls”(createacommandnamedUPLS)
exit exittheshelle.g.exit(terminatetheprogramandlogout)
expand converttabsintospacese.g.expandmyfile.txt(converttabstospacesformyfile.txt)
expand-t converttabsintospacese.g.expand-t3myfile.txt(-t:settabs3charactersapart)
export setanenvironmentvariable&valuee.g.exportnewvar=8echo$newvar(output:8)
expr evaluateanexpressione.g.expr10+8(output:18)
factor showtheprimefactorsofanumbere.g.factor1001(output:71113)
fc list,edit,re-executelastcommandse.g.fc-l(-l:listthehistoryofcommands)
fdisk* manipulatetheharddiskpartitions
e.g.fdiskdevhdb(listharddiskpartitionsinformation)
fg resumeastoppedjobinforegrounde.g.fg%3(resumethejob3inforeground)
fgrep searchfile(s)foraspecifiedstringe.g.fgrep"good"myfile.txt(searchmyfile.txtfor“good”)
file detectthefiletype.e.g.filemyfile.tar(determinefiletypeofmyfile.tar)
find –print –name
findfile(s)inadirectorynameddire.g.finddir-print-name'abc.txt'(-print:print,-name:specifyfilename)
finger showuser’sinformatione.g.fingerusername(listtheuser'sloginname,time.etc.)
fmt formattextfilese.g.fmtmyfile1.txt>myfile2.txt(formatmyfile1&outputtomyfile2)
fmt-u formattextfilese.g.fmt–umyfile.txt(-u:provideuniformwordspacing)
fold wrapeachlinetofitaspecifiedwidthe.g.fold-w15myfile.txt(-wspecifyhowmanywords)
forin setconditionalparameterforloope.g.fornin369doecho$ndone(output:369)
free displaysfreememoryinformatione.g.free(listfree,used,totalmemory…)
free-m displaysfreememoryinformation
e.g.free-m(-m:showsizesinMb.)
fsck* filesystemchecke.g.fsck(checkorfixLinuxfilesystem)
ftp transferfilesbyFileTransferProtocole.g.ftpServerURL(transferfilesusingftp)
gawk findorreplacetextinafilee.g.gawk'length($0)>88'(listlineslongerthan88characters)
grep matchaspecifiedstringorregex.e.g.greponestringmyfile.txt(searchmyfile.txtforonestring)
groups listgroupstowhichtheuserbelongse.g.groups(printthegroupsofuser)
groupadd* addanewgroupe.g.groupaddnewgroup(createanewgroup)
groupadd*-f addanewgroupe.g.groupadd–fnewgroup(-f:checkgroupdoesn’texist)
groupdel* deleteanexistinggroup.e.g.groupdelexistinggroup(removeanexistinggroup)
groupmod*-n modifyanexistinggroupe.g.groupmod-nnewgrpoldgrp(-nchangegroupname)
gunzip uncompressafilefromgzipformate.g.gunzipmyfile.txt.gz(uncompressmyfile.txt.gz)
gzip compressafiletogzipformate.g.gzipmyfile.txt(compressmyfile.txt)
halt shutdownthesysteme.g.halt
(poweroffthesystem)hash accessthehashtable
e.g.hash(listcommandsfromhashtable)
head displaysomefrontlinesinafilee.g.headmyfile.txt(outputthefirsttenlinesofmyfile.txt)
head-n displaysomefrontlinesinafilee.g.head–n4myfile.txt(-n:specifyanumberoflines)
help showhelpinformationofcommandse.g.helpecho(showinformationaboutecho)
history showthecommandshistorye.g.history(listcommandsinthisshellsession)
host findtheipaddressofadomainnamee.g.hostwebsprogram.com(showipofwebsprogram.com)
hostid displayidofthecurrenthostinhex.e.g.hostid(printthecurrenthostid)
hostname showorsetthehostnamee.g.hostname(displaythenameofcurrenthost)
id showtheuserorgroupidnumbere.g.id(displaytherootuseruid,gid.etc.)
ifconfig show,configurethenetworkinterfacee.g.ifconfig(displaythenetworksettings)
init* setthesystemrunlevele.g.init5(changetorunlevel5)
info showhelpinformationofa
commande.g.infoman(showhelppageforman)
install copyfiles,setpermission,ownershipe.g.installmyfileshomeuser(copymyfilestouserdirectory)
install-o copyfiles,setpermission,ownershipe.g.install–omyfilesray/home(-o:specifyownership)
jobs showalljobs’statuse.g.jobs(listallrunningjobs’information)
join joinlinesoffileshavingcommonfielde.g.joinmyfile1.txtmyfile2.txt(joinlinesoftwofilesbysamefield)
join joinlinesoftwofilese.g.join–imyfile1.txtmyfile2.txt(-i:ignorethedifferences)
kill stopajobbynumber.e.g.kill%3(terminatejob%3)
kill stopaprocessbypid.e.g.kill3956(terminateprocess3956)
killall stopaprocessbynamee.g.killallnorespond(terminateprocessnorespond)
last showmostrecentlylogged-inuserse.g.last(listrecentusers’date,time…)
lastb showbadloginattemptse.g.lastb(displaybadloginattempts)
lastlog displaythelastlogininformatione.g.lastlog-uusername
(-u:specifyauser)less showcontentspagebypage
e.g.lessmyfile.txt(displaymyfile.txtpagebypage)
let performarithmeticonshellvariablese.g.leta=12;leta=a+8;echo$a(output:20)
link createalinktoafile.e.g.linkfile1.txtfile2.txt(createalinkfromfile1tofile2)
ln createahardlinktoafilee.g.~/myfile.txt(createahardlinktomyfile.txt)
ln-s createalinkbetweentwofilese.g.ln-sfile1.txtfile2.txt(createasymboliclinktofile1/file2)
locate findthelocationofafileoradirectorye.g.locatemyfile.txt(locatemyfile.txtonlocalmachine)
logname showthecurrentuser’sloginnamee.g.logname(displaytheloginnameofuser)
look showwordsmatchingagivenprefixe.g.lookab(output:aba,abb,abc,abd…)
lpc runthelineprintercontrolprograme.g.lpcstatus(showstatusofcurrentprintqueue)
lpq showtheprinterqueuestatuse.g.lpq(listtheprintqueue)
lpr sendaprintrequesttoprintere.g.lprmyfile.txt(sendmyfile.txttoprinter)
lprm canceltheprintingjobinprintqueuee.g.lprm2(removeprintingjob2)
ls listthecontentsofcurrentdirectorye.g.ls(listfilesandsub-directories)
ls-l longlistcontentsofcurrentdirectorye.g.ls-l(-l:longlistsincludingpermissions)
ls-a listsallentriesincludinghiddenfilese.g.ls-a(-a:showallfiles)
ls-t listsallentriesbytimestampse.g.ls-t(-t:showbytimestamps)
ls-lh listscontentsincurrentdirectorye.g.ls-lh(-lh:listfileswithsizeinmbandgb.)
lsattr listtheattributeofafileoradirectorye.g.lsattrmyfile.txt(showmyfile.txtattribute)
lsof listopenedfilese.g.lsof(listallopenedfiles)
man getcommandhelpfrommanuale.g.mancat(showmanualpageforcat)
man-k searchmanualpagesforkeyworde.g.man–kprintf(-k:specifyakeyword)
md5sum createamd5checksumnumbere.g.md5sum-cfile.txt(-cvalidatefileagainstachecksum)
mesg enableordisablemessaginge.g.mesg(showthecurrentwritestatus)
mesgy/n enableordisablemessaginge.g.mesgy/n(yorn:permitordenymessaging)
mail sendandreceivemailse.g.mailray@websprogram.com(emailtoray@websprogram.com)
mkdir makeanewdirectorye.g.mkdirmydir(createadirectorynamedmydir)
mknod makeadevicefilee.g.mknoddevdkb450(dk:device;b:block;45:majorno.;0:minorno.)
more showcontentonescreenatonetimee.g.more+2myfile.txt(+2:beginningatline2)
mount mountastoragedevicee.g.mountdevcd(mountadevicecd)
mount-l mountorshowdevicese.g.mount-l(-l:listallmounteddevices)
mt magnetictapedrivecontrole.g.mt-fdevtapeeod(-fselecteod;movetoendofdata)
mv moveafiletoanotherdirectorye.g.mvmyfile.txthomeuser/mydir(movemyfile.txttomydirdirectory)
mv renameafilee.g.mvmyfile1.txtmyfile2.txt(renamemayfile1tomyfile2)
netstat displaynetworkstatuse.g.netstat(printnetworkconnections,routingtables.etc)
nice* settheprioritylevelofajobe.g.nice-19ftp(setprioritylevelas19forftp)
nl addtextwithnumberlinese.g.nlmylist.txt(makenumberlinesformylist.txt)
nohup ignorehangupsignalse.g.nohupfindftp(runftpignoringhangupsignals)
nslookup queryinternetnameserversforIPe.g. nslookup myxxexample.com(returnIPlike75.126.162.XXX)
passwd modifyauserpassworde.g.passwdusername(changepasswordforusername)
paste mergelinesofmultiplefilese.g.pastefile1.txtfile2.txt(mergecontentsforfile1andfile2)
pidof showprocessIDofrunningprograme.g.pidofconsole(displayconsole’sprocessid)
ping senddatatoahost,awaitresponsee.g.pingxvxmjfz.com(testifremotehostcanbereached)
ping-c testifremotehostcanbereachede.g.ping–c5xvxmjfz.com(-c5:specifythenumberofpings)
pkill killarunningprocesse.g.pkillfirefox(stopwebbrowserfirefox)
pr preparetextfilesforprintinge.g.prmyfile.txt(preparemyfile.txtforprinting)
pr-n preparetextfilesforprintinge.g.pr–nmyfile.txt(-n:specifynumberineachline)
pr-h preparetextfilesforprintinge.g.pr–h“Good”myfile.txt(-h:specifyaheader)
printenv showtheenvironmentvariablese.g.printenv(listvaluesofenvironment
variables)printf formatandprintdata
e.g.printf"start\b"(\b:backspaceoutput:star)
printf formatandprintdatae.g.printf'hello\nworld\n!'(\n:printsbynewlines.output3lines)
ps-f showtheprocessstatuse.g.ps-f(-ffullinformationofcurrentprocess)
ps-u showtheprocessstatuse.g.ps-uray(-uspecifyauser’scurrentprocess)
pstree displaysprocessintreestructuree.g.pstree(showallprocessasatree)
pwd printworkingdirectorye.g.pwd(displaycurrentdirectory)
rcp remotelycopyfilebetweentwohostse.g.rcpfile.txthost2:/dir2/file.txt(remotelycopyfile.txttohost2)
read readalinefromstandardinpute.g.readname(inputray)echo“$name”(outputray)
reboot* restartthesysteme.g.reboot(causethecomputertorestart)
renice* changetheprioritylevelofajobe.g.renice323001(setprioritylevelas3forjob23001)
restore restoresdatafromthebackupfilee.g.restore-fdatabackup
(-f:specifyabackupfile)rlogin remotelylogintoasystem
e.g.rlogin-lusernamedomain.com(-l:specifyausername)
rm removeoneormorefilese.g.rmmyfile.txt(removemyfile.txt)
rm-r removenon-emptydirectorye.g.rm-r/NonEmptyDir(-r:removedirectoryanditscontent)
rm-i removenon-emptydirectoryorafilee.g.rm-imyfile.txt(-i:askbeforeremoving)
rmdir removeemptydirectorye.g.rmdir/emptydir(deletedirectorywithoutcontents)
route showormodifytheIProutingtablee.g.route-n(-n:showinnumericalformat)
rsync remotelysynchronizefilese.g.rsyncmyfilehost2:/dir2/myfile(sync.myfilewithremotehost2)
scp securelycopyfilesamidtwohostse.g.scpfile.txthost2:/dir2/file.txt(securelycopyfiletoremotehost2)
screen opentheterminalwindowmanagere.g.screen(startanewscreen)
sdiff showtwofiles’differencesidebysidee.g.sdiffmyfile1.txtmyfile2.txt(comparetwofilessidebyside)
sed filterandtransforminputtexte.g.sed“{print$3}”myfile.txt(displaythethirdwordofeachline)
seq listsequentnumbersingivenrange
e.g.seq18(output:12345678)
seq-w listsequentnumbersingivenrangee.g.seq–w13(-w:withzerosoutput:010203)
seq listsequentnumbersingivenrangee.g.seq–s\|13(-s:withseparatorsoutput:1|2|3)
set setshellvariableorfunctione.g.setn=`whoami`;echo$n(output:whoami)
sftp securelytransferfilesbyftpe.g.sftpSeverURL(securelytransferfilestoaServer)
shopt showtheshelloptionsettingse.g.shopt(showtheshellbehaviorsettings)
shutdown* closesysteme.g.shutdown22:00(shutdownat22:00o’clock)
shutdown-h closesysteme.g.shutdown–h+5(-h+5:haltafter5minutes)
shutdown-r shutdownandrestarte.g.shutdown-rnow(-r:shutdownandinstantlyrestart)
sleep pauseforaspecifiedamountoftimee.g.sleep10(pausefor10seconds)
sort showsortedcontentsalphabeticallye.g.sort-rmyfile.txt(-rsortfileinreverseorder)
split-b splitafiletosomefilesingivensizee.g.split-b11file.txt(splitfiletosome11bytefilesnamedxaa,xab,xac,etc.)
split-l splitafiletosomefilesingivensize
e.g.split-l8file.txt(splitfiletosome8linefilesnamedxaa,xab,xac,etc.)
ssh logintoremotesecureshelle.g.sshray@myexample.com(securelyconnecttoaremotehost)
ssh-l logintoremotesecureshelle.g.ssh-lusernamehostname(-lspecifyyourremoteusername)
stat liststatusaboutfilesize,access,etc.e.g.statmyfile.txt(showmyfile.txtstatistics)
su switchusere.g.suuser2(switchusernameduser2)
su-l loginasarootsuperusere.g.su–l(-l:enterpassword,loginrootaccount)
sudo-u executeacommandasanotherusere.g.sudo-uuser2lshomemydir(-u:specifyuser2toexecutelscmd)
sudo-v refreshtheauthenticationtimeoute.g.sudo-v(next sudo will not requirepassword.)
sudo-k expiretheauthenticationtimeoute.g.sudo-k(nextsudowillrequirepassword.)
sum summarizeafilewithachecksume.g.summyfile.txt(createachecksumformyfile.txt)
suspend suspendtheworkingshelle.g.suspend(pausesystemduringexecution)
sync synchronizediskdatawithmemorye.g.sync
(flushallfilesystembufferstodisk)tac displaylinesofafileinreverse
ordere.g.tacmyfile.txt(printfilefromlastlinetofirstline)
tail showthefinalpartofafilee.g.tail-n20file.txt(-n20:outputlast20linesoffile.txt)
talk communicatewithanotherusere.g.talkray(talktouserray)
tar-xf extractanarchivedtarfilee.g.tar-xfarchive.tar(-xf:extractanarchivetarfile)
tar-cf createanarchivedtarfilee.g.tar-cfarchive.tar(-cf:createanarchivetarfile)
tee printstandardoutput,writetoafilee.g.sortfile1.txt|teefile2.txt(sortfile1.txtandwritetofile2.txt)
tee-a printstandardoutput,writetoafilee.g.sortfile1.txt|tee–afile2.txt(-a:appendinsteadofoverwrite)
test calculateabooleanexpressione.g.[8-gt6];echo$?(output:00:true;1:false)
test calculateabooleanexpressione.g.[5-eq6];echo$?(output:10:true;1:false)
time showthetimetakentorunaprograme.g.timeftp(displaythetimetakentoexecuteftp)
times showtheuptimeofselle.g.times(displaythesystemuptime)
tload showagraphicreportofsystemloade.g.tload(showthecurrent
systemloadaveragetoaspecifiedprocess)
top listthetopactiveorspecifiedprocesse.g.top-ppid(-p:displayspecificprocessbypid)
touch updatetimestampforanexistingfilee.g.touchmyfile.txt(modifymyfile.txttothecurrenttime)
touch-t updatetimestampforanexistingfilee.g.touch–tmyfile.txt(-t:specifyatime)
tr translatessetsofcharacterse.g.echoapple|tr“apple”“banana”(output:banana)
traceroute* tracetheroutetoahoste.g.traceroutexvauhdhxv.com(tracepacketsroutetoanotherhost)
trap runacommandonreceivingasignale.g.trap(displaythecurrentsignaltraps)
tree-p listdirectorycontentsintreeformate.g.tree–p(-p:alsoshowthefilepermissions)
tty showthenameoftheterminaldevicee.g.tty(showtheterminalfilename)
type detectthetypeofacommande.g.typewait(output:waitisashellbuiltin)
ulimit-a limituserresourcese.g.ulimit-a(-a:displayalllimitsforthesystem)
umask showorsetthefilepermissionvaluee.g.umask0022(allowuserread,writeprivilegesandallotherstoread)
umask showorsetthefilepermissionvaluee.g.umask0002(allowgroupread,writeprivilegesandallotherstoread)
umask showorsetthefilepermissionvaluee.g.umask0077(allowuserread,writeprivilegesandnoforothers)
umount unmountadeviceorfilesysteme.g.umountdevdvd(unmountadeviceDVD)
unalias removeanaliase.g.unaliasaliasname(deleteaspecifiedalias)
uname-a showthecurrentsysteminformatione.g.uname-a(-a:displayallinformation)
uname-n showthecurrentsysteminformatione.g.uname-n(-n:displaythehostname)
unexpand convertspacesintotabse.g.unexpandmyfile.txt(convertspacestotabsformyfile.txt)
uniq filteroutrepeatedlinesinafilee.g.uniqmyfile.txt(showuniquelineinmyfile.txt)
unset removeshellvariableorfunctione.g.unsetvar(deleteavariable)
unzip uncompressfilesfromzipformate.g.unziparchive.zip(uncompressfilefromarchive.zip)
uptime showsystemuptimee.g.uptime(displaysystemuptime)
useradd* addanewuseraccounte.g.useraddusername
(createauseraccount)useradd*-d displaydefaultvaluefornewusers
e.g.useradd-d(showdefaultdataforanewuser)
userdel* deleteanexistinguseraccounte.g.userdelusername(removeauseraccount)
usermod*-d modifyhomedirectorye.g. usermod -dhomemydirandy (-d:specifyhomedirectoryforandy.)
usermod*-l modifyanexistinguseraccounte.g.usermod-loldnamenewname(-l:loginnamechange)
usermod*-p modifyanexistinguseraccounte.g.usermod-ppasswordusername(-p:modifypasswordofauser)
users displaycurrentlogged-inuserse.g.users(listuserscurrentlyloggedin)
vdir verboselyshowdirectorycontentse.g.vdir(vdirjustlikels,butmoreverbose)
vi openthevitexteditore.g.vifilename(openafilewithvitexteditor)
vmstat reportvirtualmemorystatistics…e.g.vmstat(alsoreportswap,diski/odevices…)
w listcurrentprocessesforeachuserse.g.wusername(showtheuser’sprocess)
w-s listcurrentprocessesbysummarye.g.w-s(-s:showasummaryofshellprocess)
wait waitforaprocesstochangestate
e.g.wait10788(waitfor10788tochangestate)
watch executeacommandperiodicallye.g.watch–n5date(-n5:updatedateevery5seconds)
wc showwordcount,linecount,etce.g.wcmyfile.txt(listword,linecount…formyfile.txt)
wc-c showwordcount,linecount,etce.g.wc–cmyfile.txt(-c:showthebytecounts)
wget downloadawebpagefromawebsitee.g.wgethttp://www.xvfwkaljo.com(downloadwebpagefromaboveurl)
wget-c downloadawebpagefromawebsitee.g.wget–chttp://www.examp.com(-c:continuedownloadpreviousweb)
whatis showmanualpageofacommande.g.whatisping(showmanualpageofping)
whereis locatesource,manforacommande.g.whereisls(showsource,manlocationsofls)
which showpathofaexecutablecommande.g.whichftp(showthefullpathofftpcommand)
who showwhocurrentlyloggedine.g.who(listalllogged-inusers,date,time…)
who-a listalluserscurrentlyloggedine.g.who-a
(-a:allinformation)whoami showthecurrentuser’sloginname
e.g.whoami(showyourownusername)
whois showdomainowner’sinformatione.g.whoisxvqizx.com(listxvqizx.comowner’sinformation)
write writeamessagetoanotherusere.g.writeusername(thenwriteyourmessage…)
xargs executeacommandwithargumentse.g.find-name"a*.*"|xargsrm(findfilesnameda*.*,removethem)
xcalc launchagraphicalcalculatore.g.xcalc(openascientificcalculator)
xclock launchgraphicalclocke.g.xclock-digital(-digital:specifyadigitalclock)
yes outputastringrepeatedlyuntilkillede.g.yes“hello”(outputhellorepeatedlyuntilkilled)
yum rpm-basedpackagemanagere.g.yuminstallupdate(installapackagenamed"update")
zcat outputcompressedtexte.g.zcatmyfiles.txt.gz|less(uncompressfileandshowcontents)
zless showun/compressedfilecontentse.g.zlessmyfile.txt.gz(zless:showcontentsbypage)
zmore showun/compressedfilecontentse.g.zmoremyfile.txt.gz(zmore:showcontentsbyscreen)
zip compressfilestozipformat
e.g.zipdocuments*(createdocuments.zipforallfiles)
unzip uncompressfilesfromzipformate.g.unzipmyfile.zip(uncompressmyfile.zip.)
ConclusionMyfriends,This book is only for a basicLinux commands quick learning.Thankyou foryoursupport!Iwillgreatlyappreciateifyoukindlygiveapositivereviewtothisbook.Thankyouverymuch!BestRegardsSincerelyRayYao
Myfriend,Seeyou!
Recommended