]> GNU/Linux Command-Line Tools Summary Gareth Anderson
somecsstudent(at)gmail.com
Conversion from LyX to DocBook SGML, Index generation Chris Karakas
Linux Unix commands Linux commands Unix commands Linux tools Unix tools tutorial command line prompt command reference command tutorial command line reference command line tutorial tools tutorial tools reference tool linux command reference linux command tutorial linux command line reference linux command line tutorial linux tools tutorial linux tools reference linux tool Unix command reference Unix command tutorial Unix command line reference Unix command line tutorial Unix tools tutorial Unix tools reference Unix tool This document is an attempt to provide a summary of useful command-line tools available to a GNU/Linux based operating system, the tools listed are designed to benefit the majority of users and have being chosen at the authors discretion. This document is not a comprehensive list of every existent tool available to a GNU/Linux based system, nor does it have in-depth explanations of how things work. It is a summary which can be used to learn about and how to use many of the tools available to a GNU/Linux based operating system. 1.1 28th February 2006 CK Corrected typos, generated new index (9000 index entries!). 1.0 6th February 2006 GA Major restructuring, now in a docbook book format. Removed large chunks of content and revised other parts (removed chapters and sectioned some areas more). This is likely the final release by the author, I hope that someone finds this guide useful as I do not intend to continue work on this guide. 0.7.1 25th February 2005 CK Set special characters in math mode, produced PDF and PS with Computer Modern fonts in OT1 encoding and created correct SGML for key combinations. 0.7 5th December 2004 GA Updated document with new grammatical review. Re-ordered the entire Text section. Removed a fair amount of content. v0.6 20th April 2004 GA Attempted to fix document according to TLDP criticisms. Added notes and tips more sectioning. Now complying to the open group standards for the UNIX system trademark. Document should be ready for TLDP site. v0.5 6th October 2003 GA Fixed a variety of errors as according to the review and made some consistency improvements to the document. v0.4 15th July 2003 GA Made small improvements to the document as suggested (so far) by the thorough TLDP review, improved consistency of document and made small content additions. v0.3 26th June 2003 GA Minor errors fixed, updated the appendix with information for finding where a tool is from. Fixed referencing/citation problems and improved further reading and intro sections, added an audio section. v0.2 20th April 2003 GA This is the initial public release. Added more code-style then before, broke text-section into more subsections. Improved consistency of document and fixed various index entries. v0.1 27th March 2003 GA This is the initial draft release (the first release to be converted from LyX to DocBook SGML).
IntroductionThis document documentis an attempt attemptto summarise summarisethe many command-line-based command-line-basedtoolstools available availableto a GNU/Linux based operating operatingsystem.system This guide guideis not a complete completelisting (I doubt it's possible possibleto documentdocument all available availableprograms), this document documentlists listsmany tools toolswhich are available to GNU/Linux systems systemsand which whichare, or can be useful to the majority majorityof users.usersEach tool tooldescription descriptionprovides a quick quickoverview of it's function functionand some useful options optionsfor that individual individualtool.toolThe tools toolslisted listedthat require requirea GUI,GUI usually the X windowing windowingsystem,system are those listed listedin the Graphics GraphicsTools section.section All other tools toolsare completely command-line-based command-line-basedand do not require requirea GUI GUIto run.run If you are looking lookingfor information informationon GUI GUIbased tools toolsyou will need to looklook elsewhere.Also note that a few of the tools toolsin this guide guideare bash bash(the Bourne-Again-SHellBourne-Again-SHell) specific, tools toolsspecific specificto other shells shellsare not listed listedin this document.documentFor some of the tools toolsthat are harder to use, or perform performa more morecomplexcomplex task,task there are several severalmini-tutorials mini-tutorials(or mini-guides;mini-guides ) within this document.documentWhere a mini-guide mini-guidewas considered unncessary,unncessary detailed detaileddescriptions that explain explainin detail detailhow a particular particulartool toolworks,works and some examples examplesof how to use it are provided.providedPlease note that the word word“tool” is used interchangeably interchangeablywith the word word“command”, both have the same meaning meaning(at least leastin this guide). For a more moredetailed detailedexplanation, read readabout the UNIX UNIXTools Philosophy Philosophyhere: or visit visitthe links linksin the appendix,appendix . To find out which tools are bash specific To find out which tools are bash specific you can type: enable -a FormatsThis document documentis available availablein the following followingformats:formatsHTML (HyperText Markup Language), many HTML HTMLfiles,files one per section,section for viewing viewingwith any browserHTML (HyperText Markup Language), one big HTML HTMLfileTXT (ASCII Text)RTF (Rich Text Format)PDF (Portable Document Format)PS.GZ (Compressed Postscript)SGML (Standard Generalized Markup Language)(with the Appendix and the Bibliography)LYX (LaTeX frontend LyX)(with the Appendix and the Bibliography) RTF: Page numbers In order to get correct page numbers (and often to get the images working) in Microsoft Word, type the following after opening the document: CTRL END CTRL A F9 In Word Viewer 97, you must instead do: CTRL END ALT V N ALT V P See The OpenJade RTF backend for more details. Important: Downloads for offline reading! If you want to download the HTML or RTF formats for offline reading, you will need to download the images as well - PNG for HTML and BMP for RTF, including the callouts! To save you the hassle, I have compiled the following gzipped tar archives for offline reading: TAR.GZ (Compressed TAR Archive), many HTML files with images TAR.GZ (Compressed TAR Archive), one big HTML file with images TAR.GZ (Compressed TAR Archive), SGML file with images TAR.GZ (Compressed TAR Archive), RTF file with imagesA tarball tarballcontaining all the above is also available:available TAR.GZ (Compressed TAR Archive), All files Who would want to read this guide?Anyone who is interested in learning learningabout the tools tools(also known as commands) available availableto them when using their GNU/Linux based operating operatingsystem.systemWhy would you want to learn learnhow to use the command commandline (and available availabletools)? The Command Line Interface (CLI), while difficult to learn,learn is the quickest quickestand most efficient efficientway to use a computer computerfor many different differenttasks.tasks The CLI CLIis the normal normalmethod of use for most UNIX UNIXsystem systemadministrators,administrators programmers programmersand some power powerusers. While a GUI GUIis better suited suitedto some tasks,tasks many operations operationsare best suited to the CLI.CLIThe major majormotivation behind learning learningthe GNU/Linux CLI CLIis the authors authorsideaidea that, with software softwarein general,general the more moretime timespent learning learningsomething equals equalsless lesstime timespent performing performingthat particular particulartask task(authors opinion opiniononly).This guide guideis aimed at beginners beginnersto intermediate intermediateusers who want to learnlearn about the commandline commandlinetools available availableto them. Advanced users usersmay wish to use it as a command commandreference,reference however this document documentaims to list listcommands commandsof interest, as judged judgedby the authors authorsopinion,opinion it is not designed designedto be completely comprehensive,comprehensive see the appendix,appendix for further information.information Or if you are not looking lookingfor a command commandreference referenceguide, but a more moregentlegentle introduction introductionto GNU/Linux you may be interested in the Introduction to Linux guide authored authoredby Machtelt Garrels.GarrelsThis guide guidecould also be considered a summarised summarisedversion versionof the Linux LinuxCookbook.Cookbook If you are looking lookingfor a book bookwith more moredetailed detaileddescriptions of each tooltool have a look lookat the Linux Cookbook Homepage, also check checkout the command list from "Linux in a Nutshell 3rd Edition" for an index indexof 300+ commands commandsand their explanations.explanations Who would not want to read this guide?Anyone who is not interested in the command commandline, or anyone looking lookingfor a detailed detailedreference referenceto all available availableGNU/Linux tools toolsshould look lookelsewhere. This is only a summary,summary while it does list listmany commands,commands it's not a completecomplete listing listing(I don't think it's possible possibleto make a complete completelisting anyway).This document documentwould not be unlikely unlikelyto be of interest to those who already have an expert expertknowledge knowledgeof the command commandline interface interfaceand do require requireany reference referenceinformation.information Or those readers readerswho require requiredetailed detailedlists listsof options optionsfor each command,command the man manpages pagesare better suited suitedto this purpose.purpose Availability of sourcesThe modifiable modifiablesources sourcesof the original originalbook book(in english), are availableavailable in LyX LyXformat format(LyX Document DocumentProcessor) or Machine-translated Machine-translatedSGML SGML(SGML markup markuplanguage). LyX LyXis a completely free freedocument processor processorbased on LaTeX,LaTeX downloadabledownloadable from the LyX homepage..See for the modifiable modifiablesources sourcesof this document.document These are the official officialversions.versions We (the translators translatorsand current currentmaintainers) plan planto continue work workon this document documentand add addnew newchapters and enhancements.enhancements If you want to see the version versionwe are currently working workingon (the "bleeding edge" version), check checkthe GNU/Linux Command-Line Tools Summary Homepage from time timeto time time(kindly hosted hostedby Chris Karakas). Conventions used in this guidesansThe following followingconventions conventionsare used within this guide:guide italic italicAnything appearing in italic, like this is either an executable executablecommand commandor emphasized emphasizedtext.text Tools Tools(executable commands) are in italics italicsto prevent preventconfusion. Some tools toolshave names which whichare real realenglish englishwords,words such as the “locate” tool.toolkey  combinations combinationsAre represented representedby using a '-' (dash sign) inbetween the key(s), which whichmust mustbe used in combination.combination All combinations combinationsare also printed printedin italics italicsto improve improveclarity.clarity For example example CTRL Z CTRL-Z means hold down the Control Controlkeykey and press pressthe z key. admonitions admonitionsAdmonitions are little pictures picturesused to emphasize emphasizesomething of importance importanceto the reader.reader The five fivetypes used are: This is a note Notes often give important information about a tool. This is a tip This will offer a useful switch or useful way to use a tool. This is something important This is something that is considered very important. Consider it like a note with extra importance, they are usually there to save the reader time. This is a caution This will inform you of something that you be careful about (because it could be harmful to your system). This is a warning This will inform you of something that you shouldn't do (because it probably will break something within your system). code examples Code Codeexamples examplesare shown shownfor most commands.commands Below is an example exampleof what code codelooks like:command  syntax syntax(or a similar similarphrase) simply shows showshow you would normally use the command.command Often real realexamples examplesare used instead of explaining explainingthe command commandsyntax.syntax The phrase phrase“ Command Commandsyntax” is always followed followedby the way you would type a command commandin a shell.shellThe standard standardsyntax syntaxfor any tool toolis usually: Note Note that some tools do not accept options. wildcards wildcardsAlso note that most commands,commands even evenwhen not explicitly explicitlystated,stated will work workwith standard standardwildcards standard wildcardswildcards(or globbing globbingpatterns) such as *, [A-Z] and various other standard standardwildcards.standard wildcardswildcards Refer Referto for further information.informationaccess  keys keysAccess Accesskeys enable enablenavigation through the document,document without relying on a mouse.mouse The following followingkeys have been given special specialmeaning meaningin this document:documentP Previous Previouspage.pageN Next Nextpage.pageH Home Homeof the document document(Table of Contents).U Up (takes you one level levelup the section sectionhierarchy).If you also happen to be reading readingthe document documentfrom its original originallocation,location then the following followingaccess accesskeys can also be used:S Start Start(takes you to the author's start startpage).T The current current(“This”) page,page without the Sitemenu Sitemenuon the left.leftM The current currentpage pagein a frameset,frameset where the left leftframe framecontains a Menu.Menu To use the access keys, you have to simultaneously press a modifier key, which may vary from browser to browser. For example in NN6+/Mozilla, the modifier key is ALT, so you have to use ALT N to go to the next page, and ALT P to come back. In other browsers such as IE6, the access keys just give focus to the associated link, so the sequence becomes ALT N Enter . Try it, you'll like it! ]]> ]]> ]]> ]]> Inline graphic Resources used to create this document To create the GNU/Linux Command-Line Command-LineTools Summary,Summary I used LyX, the document documentprocessor.processor To convert convertthe LyX LyXfiles filesto DocBook DocBookSGML SGMLI used the LyX-to-X Scripts created by Chris Karakas.Karakas, ChrisYou may also want to check checkout the db2lyx package,package created by Dr. B Guillion,Guillion, B. Dr. which whichcan be used to convert convertLyX files filesto XML XMLDocBook and XML DocBook DocBookto LyX.LyX I also had assistance assistancefrom various The Linux Documentation Project volunteers volunteers(see the contributors contributorssection section for specific specificdetails). FeedbackFeedback Feedbackis necessary for the advancement advancementof this guide.guide Positive,Positive constructive criticism criticismis encouraged.encouraged If you have ideas,ideas suggestions,suggestions advice,advice or problems problemswith this guide,guide please send sendan email emailto the author authorGareth Anderson. Anderson, Gareth Contributions If you wish to make contributions it is recommended (if possible) to read the LyX file(s) for this document. They contain various notes which you can't see in the other versions. These notes highlight the areas that need contributions, certain tools which I cannot understand, tools which have not been added, or tools which were removed. These notes also explain some of the structure of this document. Contributors As you may be able ableto see, parts partsof this guide guideare based off offvarious adviceadvice columns columnson GNU/Linux, anything that has being directly quoted quotedfrom an articlearticle can be found foundin the references,references , section sectionof this document.document The following followingis a list listof people peoplewho have made a significant significantcontributioncontribution to this document,document in a rough roughchronological chronologicalorder.Chris Karakas: ChrisKarakas, Chris allowed allowedthe use of his lyxtox lyxtoxscripts scriptsto convert convertthe LyX LyXfile of the document documentto working workingDocBook SGML SGMLoutput (to learn learnhow to use the lyxtoxlyxtox scripts scriptsyourself, see Document processing with LyX and SGML).Chris provided provideduseful suggestions suggestionsand advice,advice and added an index indexlistinglisting for many of the commands.commands Chris is also responsible responsiblefor the great greatlooking HTML HTMLfile for this documentdocument (the CSS CSSfile and HTML HTMLcustomisations customisationsare completely his work).Chris has also helped helpedfix up problems problemsin the document document(many times), especiallyespecially with docbook/sgml related problems problemsand LyX LyXrelated issues.issuesChris has also improved improvedthe structure structureof the document documentby adding addinglabels and fixing fixingminor minorerrors.William West: William West, Williamprovided a thorough review reviewof the document documentas requiredrequired by the Linux Documentation Project. He is responsible responsiblefor a variety varietyof improvements improvementsto the quality qualityof this document.documentHis contributions contributionsinclude:include Improvements Improvementsto the readability readabilityof this document.document Improvements Improvementsto the structure structureand consistency consistencyof this document.document Various grammar grammarimprovements throughout the document.document Repair Repairof some minor minortechnical errors.errorsTabatha Persad: Persad, TabathaTabatha, as the Linux Documentation Project Review ReviewCoordinator (at the time) also gave gavea brief review reviewof this document.document Her general generaladvice was used to improve improvethe structure,structure language languageand grammargrammar of the document.documentRahul Sundaram: Sundaram, RahulRahul provided provideda brief review reviewof this document documentfor the Linux Documentation Project. Advice from his brief review reviewwas integrated integratedinto this document documentto improveimprove readability readabilityand structure,structure several severalreferences referenceswere added as recommendedrecommended by Rahual.David Lawyer: Lawyer, DavidDavid's criticism criticismof the document document(via the TLDP TLDPdiscuss discusslist) were listened listenedto, and attempts attemptsto improve improvethe document documentwere made. A number numberof his criticisms criticismswere addressed addressedand improved.improved George Harmon: Harmon, GeorgeGeorge provided provideda second language languagereview.review His detailed detailedreview of the material materialallowed allowedme to improve improvethe general generalgrammargrammar of the document documentand some minor minorerrors.Machtelt Garrels (tille): Garrels, MachteltMachtelt provided providedtips in regard regardto referencingreferencing the correct correctLDP documents documentsfrom this guide.guide As well as general generaladvice on improvements improvementsto the guide.guide LegalThe legal legalchapter provides providesinformation informationabout the disclaimer disclaimerthat applies to the entire entiredocument and the licensing licensinginformation.informationDisclaimerNo liability liabilityfor the contents contentsof this documents documentscan be accepted.accepted Use the concepts,concepts examples examplesand other content contentat your own risk.risk There may be errors errorsand inaccuracies,inaccuracies that may of course be damaging to your system.system Although this is highly highlyunlikely,unlikely you should proceed proceedwith caution.caution The author authordoes not accept acceptany responsibility responsibilityfor any damage damageincurred.All copyrights copyrightsare held by their respective respectiveowners, unless unlessspecificallyspecifically noted otherwise. Use of a term termin this document documentshould not be regarded regardedas affecting the validity validityof any trademark trademarkor service servicemark. Naming Namingof particular particularproducts productsor brands brandsshould not be seen as endorsements.endorsements UNIX UNIXis a registered registeredtrademark trademarkof The Open OpenGroup. License Copyright Copyright© 2003 - 2006 Gareth Anderson.Anderson Permission Permissionis granted grantedto copy,copy distribute distributeand/or modify modifythis document documentunder the terms termsof the GNU GNUFree FreeDocumentation License,LicenseGNU Free Documentation License} Version Version1.1 or any later version versionpublished by the Free FreeSoftware Foundation;FoundationFree Software Foundation} with no Invariant InvariantSections,Sections with no Front-Cover Front-CoverTexts, and with no Back-Cover Back-CoverTexts.Texts A copy copyof the license licensecan be found foundin the section sectioncalled the GNU GNUFree FreeDocumentation License Licenseor at the GNU Documentation License Site. The Unix Tools PhilosophyA tool toolis a simple program,program usually designed designedfor a specific specificpurpose, it is sometimes referred referredto (at least leastthroughout this document) as a command.commandThe “ Unix Unixtools toolsphilosophy” emerged emergedduring the creation creationof the UNIX UNIXoperating system,system after the breakthrough invention inventionof the pipe pipe'|' (refer to for information informationon using the pipe).The pipe pipeallowed the output outputof one program programto be sent to the input inputof another. The tools toolsphilosophy was to have small smallprograms programsto accomplish accomplisha particularparticular task taskinstead of trying tryingto develop developlarge monolithic monolithicprograms programsto do a large number numberof tasks.tasks To accomplish accomplishmore morecomplex complextasks,tasks tools toolswould simply be connected connectedtogether,together using pipes.pipesAll the core coreUNIX UNIXsystem systemtools were designed designedso that they could operateoperate together.together The original originaltext-based text-basededitors (and even evenTeX TeXand LaTeX) use ASCII ASCII(the American Americantext encoding encodingstandard; an open openstandard) and you can use toolstools such as; sed, awk, vi, grep, cat, more, tr and various other text-based text-basedtools in conjunction conjunctionwith these editors.editors Using this philosophy philosophyprogrammers programmersavoided writing writinga program program(within their larger program) that had already been written writtenby someone else (this is sometimes called code coderecycling). For example,example command commandline spell spellcheckers are used by a number numberof differentdifferent applications applicationsinstead of having each application applicationcreate its own own spellspell checker.checkerThis philosophy philosophylives on today todayin GNU/Linux and various other UNIX UNIXsystem-based operating operatingsystems systems(FreeBSD, NetBSD,NetBSD OpenBSD,OpenBSD etc.).For further information information(articles) on the UNIX UNIXtools philosophy philosophyplease see the further reading readingsection,section here: Shell TipsThe shell shelltips chapter provides provideshandy tricks tricksthat you may wish to use when you are using a GNU/Linux shell shell(the command commandline interface). This information informationincludes handy handyshortcut shortcutkey combinations,combinations the shell's command commandhistory and information informationon virtual virtualterminals. If you can't boot into your system If your having problems booting into your system you may like to use a shell so you can boot into your system and attempt to fix things up again. To do this you need to pass the “init=/bin/sh” to your system before you boot up. If you don't know how to do this please see , the technique is the same except this time you pass "init=bin/sh" rather than "single". General Shell TipsAutomatic Command  Completion CompletionUse the TAB TABkey and BASH BASHwill attempt attemptto completecomplete the command commandfor you automatically.automatically You can use it to complete completecommand (tool) names. You can also use it when working workingwith the file-system,file-system when changing directories, copying copyingfiles et cetera.ceteraThere are also other lesser lesserknown ways to use automatic automaticcommand completioncompletion (for example examplecompleting completinguser usernames):This information was adopted (with editing) from Mandrakesoft's Command Line Manual, see [7] in the for further information. ESC Y ESC-Y  (Y: special character) Will attempt attemptto complete completethe command commandname for you. If it fails failsit will either list listthe possible possiblecompletions completions(if they exist). If there are none noneit will simply beep beep(and/or) flash flashthe screen.screen CTRL X Y CTRL-X-Y  (Y: special character) Lists Liststhe possible possiblecompletions completions(it won't attemptattempt to complete completeit for you) or beep beepif there are no possible possiblecompletions.completionsSpecial-characters:Use the following followingspecial specialcharacters combined combinedwith either ESC Y ESC-Y or CTRL X Y CTRL-X-Y , where Y is some special specialcharacter.character For example example ESC $ ESC-$ or CTRL X $ CTRL-X-$ to complete completean environment environmentvariable name.~ (tilde) tilde~complete completea user username@ (at sign) at, sign@complete completea machine machinename$ (dollars sign) dollar sign$complete completean environment environmentvariable name! (exclamation mark) exclamation mark!a magic magiccharacter characterfor completing completinga command commandname or a file filename (/). The ! special specialcharacter characterhas the same function functionas the TAB TABkey. It works worksin some other situations; for example examplewhen completing completingman pagepage names. alias aliasThe alias command commandwill list listyour current currentaliases.aliases You can use unalias to remove removethe alias alias(to disable disableit just for one command commandadd a “\” (back-slash) before the command)...An alias aliasallows allowsone command commandto be substituted substitutedfor another. This is used to make a command commanddo something else or to automatically automaticallyaddadd certain options.options This can be either be done during one session sessionusing the alias aliascommand command(see below) or the information informationcan be added to the .bashrc file file(found in the users usershome homedirectory).Below is an example exampleof what an alias aliassection section(within your .bashrc file) might look looklike:On any Mandrake/Mandriva Linux Linuxsystem systemthe global globalaliases aliases(for all users) are all in /etc/profile.d/alias.sh. The above listed listedcommands already have aliases,aliases as well as several severalother commonly commonlyused commands.commandsset  -x -x set setis one of bash's inbuilt inbuiltcommands,commands try trylooking in the bash bashmanual for its many usage usageoptions.optionsUsing set with the -x -x option optionwill make bash bashprint out each command commandit is going to run runbefore it runs runsit. This can be useful to find findout what is happening with certain commands commandssuch as things being quoted quotedthat contain wildcards wildcardsor special specialsymbols symbolsthat could cause causeproblems, or complex complexaliases.aliases Use set set+x to turn turnthis back off.offExamplesAfter using set set-x you can run runthe command:commandThe output outputprinted printedbefore the command commandruns (for example):Which means that the command commandis really reallyan alias aliasto run runls with the -F and --color=auto options.options Use a “\” (backslash) before the command commandto run runit without the alias.alias\ (backslash) \The backslash backslashescape character charactercan be used before a shell shellcommand to override overrideany aliases.aliasesFor example exampleif rm was made into an alias aliasfor rm rm-i-i then typing “rm” would actually run run rm rm-i-i. However, typing \rm lets the shell shellignore the alias aliasand just run runrm (its runs runsexactly what you type), this way it won't confirm confirmif you want to delete deletethings. Using rm Please note that the alias for the remove command is there for a reason. Using it incorrectly could remove files which you don't want removed. Only use \rm if you know exactly what you are doing (recovering files is not easy, rm does not send things to a recycle bin). The “\” character charactercan be used before special specialcharacters (such as a space spaceor a wildcard.wildcard..) to stop stopbash bashfrom trying tryingto expand expandthem (a directory directoryname with a spacespace in it is possible possiblethis way). For example exampleyou could type cd My\ DirectoryDirectory\ With\ SpacesSpaces which whichnormally wouldn't work.work The “\” character charactercan also be used to stop stopbash bashfrom expanding expandingcertain symbolssymbols (as an alternative alternativeyou could use single quotation quotationmarks, although you may need to use both). The TAB Key Please note that using the TAB key (automatic-command-completion) will automatically use escapes for spaces (so you don't have to type them manually). script scriptThe “script” command commandcreates a typescript,typescript or "capture log" of a shell shellsession - it writes writesa copy copyof your session sessionto a file,file including includingcommands commandsyou type and their output.output~ (tilde character) ~The tilde tildecharacter characteris used as an alias aliasto a users usershomehome directory.directory For example,example if your user-name user-namewas “fred”, instead of typing cd cd/home/fred you could simply type cd cd~. Or to get to fred's tmp tmpdirectory directory(under his home homedirectory) you could type cd cd~/tmp. Home directory shortcut ~ (tilde) can also be used as a shortcut to other users home directories, simply type: ~user_name and it will take you to the user's home directory. Note that you need to spell the username exactly correct, no wildcards.  set bell-style  none set bell styleThis particular particularset command commandwill turn turnoff offthe system systembell from the commandline commandline(use xset xset-b for X windows). If you want the bell bellto stay off offpernamently (no audible audiblebell) then you can add addthis command commandto your “.bashrc” or “.bash_profile” (just add it to the same one you have your alises in...). reset resetThe reset command commandre-initializes your current currentterminal.terminal This can be useful when the text textfrom your terminal's text textbecomes garbled,garbled simply type “reset” and this will fix fixyour terminal.terminal exit exitCloses your current currentterminal terminal(with x-terminals) or logs-out.logs-out Also try try CTRL D CTRL-D . logout logoutLogs out of a terminal,terminal also try try CTRL D CTRL-D . echo echoA little command commandthat repeats repeatsanything you type.Example:Simply displays “ hello helloworldworld”. Example:This will output outputwhat will be passed passedto the rm command command(and therefore what would be deleted), putting puttingecho before a command renders rendersit harmless harmless(it just expands expandswildcards wildcardsso you know what it will do).Also try tryusing the -e -e option optionwith echo.echo This will allow allowyou to use the escape escapecharacter charactersequences to format formatthe output outputof a line.line Such as '\t' for tab,tab '\n' for newline newlineetc. Using echo to prevent accidents Typing: echo command(s) could save you the trouble of accidentally doing something you didn't expect. Using echo allows you to expand the wildcards to understand what will happen before you actually run the command. The command-line historyUsing the command  history historyUse the up and down key's to scroll scrollthrough previously typed commands.commands Press Press[Enter] to execute executethem or use the left leftand right arrow arrowkeys to editedit the command commandfirst. Also see history (below).The history  command commandThe history history command commandcan be used to list listBash's log logof the commands commandsyou have typed:This log logis called the “history”. To access accessit type:This will only list listthe last lastn commands.commands Type “history” (without options) to see the the entire entirehistory list.listYou can also type !n to execute executecommand commandnumber n. Use !! to execute executethe last lastcommand you typed.!-n will execute executethe command commandn times timesbefore (ie. !-1 is equivalent equivalentto !!). !string will execute executethe last lastcommand starting startingwith that “string” and !?string? will execute executethe last lastcommand containing the word word“string”. For example:exampleWill re-run the command commandthat you last lasttyped starting startingwith “cd”.“ commandName commandName!*” will execute executethe “commandName” with any arguments argumentsyou used on your last lastcommand. This maybe useful if you make a spelling spellingmistake, for example.example If you typed:In an attempt attemptto execute executeemacs emacson the above two files filesthis will obviously fail.fail So what you can do is type:This will execute executeemacs emacswith the arguments argumentsthat you last lasttyped on the commandcommand line.line In other words wordsthis is equivalent equivalentto typing:Searching through the Command History ( CTRL R CTRL-R ) Use the CTRL-R key keyto performperform a “reverse-i-search”. For example,example if you wanted to use the command commandyou used the last lasttime you used snort, you would type: CTRL R then type “snort”. What you will see in the console consolewindow windowis:romanAfter you have typed what you are looking lookingfor, use the default CTRL R CTRL-R key keycombination to scroll scrollbackward through the history.history romanUse default CTRL R CTRL-R repeatedlyrepeatedlyroman to find finddefaulteveryroman reference referenceto the string stringyou've entered.entered Once you've found foundthe command commandyou're looking lookingfordefault,roman use [Enter] to execute executeit. Alternatively, romanusing the right or left leftarrow keys keyswill place placethe command commandon an actual actualcommand line lineso you can default edit editit. Other Key combinationsGNU/Linux shells shellshave many shortcut shortcutkeys which whichyou can use to speed speedup your work,work below is a rough roughlist of some (also see CTRL-R the history historysectionsection of the commands,commands over here, ). The CTRLD the “end-of-file” (EOF) key combination can be used to quickly log out of any terminal. CTRL-D is also used in programs such as “at” to signal that you have finished typing your commands (the EOF command). The CTRLZ key combination is used to stop a process. It can be used to put something in the background temporarily. For example, if you were editing a file with vim or emacs just press CTRL-Z to regain control of the terminal do what you want and then type fg to bring it back. For further information please see . If <emphasis>fg</emphasis> doesn't work If fg doesn't work you may need to type jobs and then fg job_name or fg job_number The CTRLA and CTRLE key combinations are used for going to the start and end of the line on the command line. Use CTRLA to jump to the start of the line, and CTRLE to jump to the end of the line. The CTRLK key combination can be used to cut or delete what is currently in front of the cursor. The CTRLY key combination can be used to paste the last thing you deleted (using CTRL K CTRL-K or CTRL W CTRL-W ). The CTRLW key combination can be used to cut or delete the entire line that has being typed. Virtual Terminals and screenUsing the key combination ALT F* keys you may change to different virtual terminals. You will have several (usually 6) virtual terminals setup with shells. Number 7 is usually setup with X you need to use CTRL ALT F* CTRL-ALT-F* to change to a terminal from within X (X as in the X windowing system). screen screenis a great greatprogram that allows allowsyou to switch switchbetween multiple multiplevirtualvirtual terminals terminalson the one physical physicalterminal terminalthat you are using. Its a command-line command-linebased window windowmanager, clearly this isn't that useful if you do have virtual virtualterminals, but its amazingly useful when you loglog into machines machinesremotely, using ssh sshand similar,similar see . It works workson key-combinations,key-combinations you typeOn the command-line to begin. Now you start with one virtual terminal by default, but using the key combination CTRL A and then hitting "C" you can create another virtual terminal to use. Use CTRLN to go to the next virtual terminal and CTRLP to go to the previous virtual terminal. Also try hitting CTRLA to go backwards and forwards between two particular terminals. screen screenalso has various other abilities abilitiesthat you can test testout. The documentation documentationand guides are well written writtenso please feel free freeto readread the manual manualpage pageor try trysearching the internet.internet HelpThe help helpchapter provides providesinformation informationon how you may access accessthe documentationdocumentation of the GNU/Linux system.system There is normally a document documentdescribing every single tool toolyou have installed,installed even if its only brief... man manThis command commanddisplays summary summaryinformation informationon a program programfrom an onlineonline manual.manual For example exampletyping man man manwill bring up the manual manualpage pagefor man man(the manual manualpage pageviewer). Note: q is the quit quitkey. Command Commandsyntax: Also try Specifying the section of the manual page, sometimes the man page is different for the same tool in different sections, note sections are numbered 1 to 9. Use apropos to find which section number to look in. The syntax to look at a different section is: man section_number tool_name For example: man 2 time This will show you the man page called time in section 2, the equivalent page in section 1 is completely different man -K  keyword keywordSearch Searchthe manual manualpages for a string,string as in it will searchsearch all manual manualpages for a particular particularstring stringwithin each individual individualman manpage,page it will then prompt promptwhether you would like to view vieweach page pageit will find.find Use double doublequotes “ and ” if there are spaces spacesin the string stringyou are typing. Speed issue Please be warned that this method is going to be really, really slow. You are searching *all* man pages for a string man -f  command commandThis will list listdetails detailsassociated associatedwith the command. The root rootuser usermust run runmakewhatis (see below) before this command commandwill work.work Equivalent to <emphasis>whatis</emphasis> This command is the same as running whatis info infoProvides a more moredetailed detailedhyper-text manual manualon a particular particularcommand,command this only works worksfor some commands.commands Command Commandsyntax: whatis whatisDisplays a one line linedescription descriptionof what a program programdoes. The string stringneeds to be an exact exactmatch, otherwise whatis won't output outputanything. Relies on the whatis whatisdatabase (see below). Command Commandsyntax: makewhatis makewhatisMake the whatis whatisdatabase for apropos, whatis and man man-f.-f Root Privileges This takes some time and you require root privileges to do this. apropos aproposSearches Searchesthe whatis whatisdatabase for strings,strings similar similarto whatis except it finds findsand prints printsanything matching matchingthe string string(or any part partof the string). Also relies on the whatis whatisdatabase (see above). Command Commandsyntax: Equivalent to... apropos is the same as doing man -k (lowercase k). Please note You need to run makewhatis (as root) so whatis, man -f and apropos will work. Also try Using a program with the -?, --h, --help, and the -h options, they will display very short summary information on the command usage options. Directing Input/OutputThe directing input/output chapter explains explainshow you can use a program programand send sendits output outputto a file fileor to another command commandthat you wish to use. This technique techniqueis very powerful powerfuland there are a number numberof ways of doing this.Concept DefinitionsAll three of the following followingdefinitions definitionsare called “ File FileStreams.Streams” They hold information informationthat is either received receivedfrom somewhere or sent to somewhere. In a UNIX UNIXsystem,system the keyboard keyboardinput (standard input), information informationprinted to the screen screen(standard output) and error erroroutput output(also printed printedto the screen) are treated treatedas separate separateFile Streams.StreamsStandard output Standard standard outputoutput output, standardis the output outputfrom the program programprinted printedto the screen,screen not including includingerror output output(see below).Standard input Standard standard inputinput input, standardis the input inputfrom the user.user Normally the keyboard keyboardis used as the standard standardinput inputstandard inputdevice in a UNIX UNIXsystem.systemStandard error Standard Standarderror erroris error erroroutput outputfrom programs.programs This output outputis also sent to the screen screenand will normally be seen mixedmixed in with standard standardoutput.standard outputoutput The difference differencebetween standard standardoutput standard outputoutputand standard standarderror standard erroris that standard error erroris unbuffered unbuffered(it appears immediately on the screen) and standardstandard error erroris only printed printedwhen something goes wrong wrong(it will give you detailsdetails of what went wrong). Usage> >The greater greaterthan symbol symbolis used to send sendinformation informationsomewhere (for exampleexample a text textfile)Example: file1_and_2.txt ]]>This will concatenate concatenatethe files filestogether into one big file filenamed named“file1_and_2.txt”. Note that this will overwrite overwriteany existing existingfile.< <The less lessthan symbol symbolwill insert insertinformation informationfrom somewhere (a text textfile) as if you typed it yourself. Often used with commands commandsthat are designed designedto get information informationfrom standardstandard input inputonly.For example example(using tr): fileNameNew.txt ]]>The example exampleabove would insert insertthe contents contentsof “fileName.txt” into the input inputof tr and output outputthe results resultsto “fileNameNew.txt”.>> >>The >> symbol symbolappends (adds) information informationto the end endof a file fileor creates one if the file filedoesn't exist.exist<< <<The << symbol symbolis sometimes used with commands commandsthat use standard standardinputinputstandard input to take takeinformation.information You simply type << wordword (where word wordcan be any string) at the end endof the command.command The command commandtakes your input inputuntil untilyou type “word”, which whichcauses the command commandto terminate terminateand process processthe input.input Using << is an alternative alternativeto using CTRL D CTRL-D (EOF key), except it uses a string stringto perform performthe end-of-file end-of-filefunction.functionFor example type "cat" (with no options...) and it will work workon standard standardinput.inputstandard inputTo stop stopentering standard standardinput inputstandard inputyou would normally hit hit CTRL D CTRL-D .As an alternative alternativeyou can type "cat << FINISHED", then type what you want. When you are finished,finished instead of hitting hitting CTRL D CTRL-D you could type "FINISHED"FINISHED and it will end end(the word wordFINISHED will not be recorded).2> 2>Redirects error erroroutput.output For example,example to redirect redirectthe error erroroutput outputto /dev/null, so you do not see it, simply append this to the end of another command...For example:example /dev/null ]]> Runs Runsmake on a file fileand send sendall error erroroutput outputto /dev/null| |The “pipe” pipecommand commandallows allowsthe output outputof one command commandto be sent to the input inputof another.For example:example Concatenates Concatenatesthe files filestogether, then runs runsless on them. If you are only going to look lookat a single file,file you would simply use less on the file... tee teeSends Sendsoutput of a program programto a file fileand to standard standardoutput.standard outputoutput Think of it as a sansTdefault intersection...it goes two ways.For example:example Lists Liststhe files files(displays the output outputon the screen) and sends sendsthe output to a file:file “my_directories.txt”.&> &>Redirects Redirectsstandard output, standardoutput standard outputoutputand error erroroutput output, errorto a specific specificlocation.locationFor example:example /dev/null ]]> Sends Sendsboth error erroroutput outputand standard standardoutput standard outputoutputto /dev/null so you won't see anything... Command SubstitutionCommand Commandsubstitutionsubstitution, commandcommand substitution is basically basicallyanother way to do a pipe,pipe you can use pipes pipesand command commandsubstitution interchangeably,interchangeably it's up to you which whichone you find easier... Command Commandsubstitution can be done in two distinct distinctways.  Method One (back-quotes)  Simply type:This will execute execute“command_2” and it's output outputwill become the input inputto “command_1”. Backquote key The back-quote key is usually located at the same place as the tilde, above the [Tab] key. Method Two (dollars sign)  Simply type:This will execute execute“command_2” and it's output outputwill become the input inputto “command_1”.Using the pipe instead  You can of course use pipes pipesto do the same thing, if you don't know what a pipe pipeis, please see . For example exampleinstead of doing:You could do:And end endup with exactly exactlythe same result,result it's up to you which whichway you findfind easier. Performing more than one commandExecuting the second command only if the first is successful&&command, more than one  To do this you would type:command2 command2will be executed if command1 command1successfully completes (if command1 fails failscommand2 command2won't be run). This is called a logical logicalAND.ANDExecuting the second command only if the first fails||  To do this you would type:command2 command2will be executed if command1 command1does not successfully successfullycompletes (if command1 command1is successful successfulcommand2 won't be run). This is called a logical logicalOR.ORExecuting commands sequentially;  To execute executecommand commandsequentially sequentiallyregardless of the success/failure of the previous previousyou simply type: command2 command2will execute executeonce command1 command1has completed. More than two commands You can continue to use ';' (semicolon) characters to do more and more commands on the one line. Working with the file-systemThe working workingwith the file-system file-systemchapter explains explainsa number numberof commands commandsthat you use to move movearound the file filesystem systemhierarchy hierarchyand manipulate manipulatethe files.files Also explained are finding findingfiles filesand how to mass-rename mass-renamefiles.Moving around the filesystem cd cdChange Changedirectory.directory Use “ cd cd..” to go up one directory.directory One dot dot'.' represents representsthe current currentdirectory directorywhile two dots dots'..' representrepresent the parent parentdirectory.directory “ cd cd-” will return returnyou to the previous previousdirectory (a bit bitlike an “undo”). You can also use cd absolute path or cd relative path (see below):Absolute  paths pathsAn “ absolute absolutepathpath” is easily recognised recognisedfrom the leading leading/. The / means that you start startat the top toplevel directory directoryand continue down.For Example Exampleto get to /boot/grub you would type:This is an absolute absolutepath pathbecause you start startat the top topof the hierarchy hierarchyand go downwards downwardsfrom there (it doesn't matter where in the filesystem filesystemyou were when you typed the command).Relative  paths pathsA “ relative relativepath” doesn't have a preceding precedingslash. Use a relative relativepath when you start startfrom a directory directorybelow the top toplevel directory directorystructure. This is dependent dependenton where you are in the filesystem.filesystemFor exampleexample if you are in root's home homedirectory directoryand want to get to /root/music, you type:Please note that there is no / using the above cd cdcommand. Using a / would cause causethis to be an absolute absolutepath,path working workingfrom the toptop of the hierarchy hierarchydownward. ls lsList files filesand directories.directories Typing “ls” will list listfiles filesand directories, but will not list listhidden hiddenfiles filesor directoriesdirectories that start startwith a leading leading'.'. Example Exampleoptions:optionsls ls-l --- long longstyle,style this lists listspermissions, file filesize,size modification modificationdate,date ownership.ownership ls ls-a --- this means "show all", this shows showshidden hiddenfiles,files by default defaultany filefile or directory directorystarting startingwith a '.' will not be shown.shown ls ls-d --- list listdirectories directoriesonly (see example examplebelow) ls ls-F --- append appendsymbols symbolsto particular particularfiles,files such as * (asterisk) for executableexecutable files.files ls ls-S --- sort sortthe output outputof the command commandin decending decendingorder ordersorted sortedby size.size ls ls-R --- (recursive) to list listeverything everythingin the directories directoriesbelow as well as the current currentdirectory.directory Command Commandsyntax, either:This simply lists listseverything in the current currentdirectory,directory the options optionsare not required required(options such as -l, -a et cetera).This lists listsfiles using a certain string.string The string stringcan contain standard standardwildcards standard wildcardswildcardsto list listmultiple files,files to learnlearn more moreabout standard standardwildcards standard wildcardswildcardsplease read readYou can use ls ls-d to show showdirectories that match matchan exact exactstring, or use standard standardwildcards.standard wildcardswildcards Type “ ls ls-d */” to list listall subdirectories subdirectoriesof the current currentdirectory.directory Depending Dependingon the setup setupof your aliases aliases(see ) you may simply be able ableto type lsd lsdas the equivalent equivalentto ls ls-d */. Examples Examplesfor ls ls-d: Lists Listsall subdirectories subdirectoriesof current currentdirectory.directory Lists Listsdirectories that start startwith "string"string. Lists Listsall directories directoriesthat are two levels levelsbelow the /usr/ directory directoryand have a directory directorycalled “doc”, this trick trickcan come in quite quitehandy sometimes. You can also use Depending on how your aliases (see ) are setup you can also use l, la (list all) and ll (list long) to perform the above commands pwd pwdPrint Printworking workingdirectory. Print Printthe absolute absolute(complete) path pathto the directory directorythe user useris currently in. Command Commandsyntax:This will tell tellyou the full fullpath pathto what directory directoryyou are in, for exampleexample it may output output“/usr/local/bin” if you are currently in that directory.directorytree Outputs Outputsan ASCII ASCIItext tree treegraph graphstarting startingat a given directory directory(by default defaultthe current currentdirectory). This command commandrecursively lists listsall files filesand all directories.directoriesIn other words,words it will list listfiles fileswithin the directories directoriesbelow the currentcurrent one, as well as all files filesin the current currentdirectory.directorytree has a large number numberof options,options refer referto the manual manualpage pagefor details.details Command Commandsyntax:orFinding files find findfind is a tool toolwhich looks looksfor files fileson a filesystem.filesystem find has a large number numberof options optionswhich can be used to customise customisethe searchsearch (refer to the manual/info pages).Note that find findworks workswith standard standardwildcards,standard wildcardswildcards , and can work workwith regular regularexpressions, . Basic Basicexample:This would look lookfor a file filenamed named“file” and start startat the root rootdirectory directory(it will search searchall directories directoriesincludingincluding those that are mounted mountedfilesystems).The `-name' option optionis case sensitive sensitiveyou can use the `-iname' option optionto find findsomething regardless regardlessof case.Use the '-regex' and '-iregex' to find findsomething according to a regular regularexpression (either case sensitivesensitive or case insensitive insensitiverespectively).The '-exec' option optionis one of the more moreadvanced advancedfind findoperations.operations It executes a command commandon the files filesit finds finds(such as moving movingor removingremoving it or anything else...).To use the -exec option:option use find findto find findsomething, then add addthe -exec option optionto the end,end then: command_to_be_executed then '{}' (curly brackets) then the arguments (for example a new directory) and finally a ';' . See below for an example exampleof use this command.command This is the tool you want to execute on the files find locates. For example if you wanted to remove everything it finds then you would use -exec rm -f The curly brackets are used in find to represent the current file which has been found. ie. If it found the file shopping.doc then {} would be substituted with shopping.doc. It would then continue to substitute {} for each file it finds. The brackets are normally protected by backslashes (\) or single-quotation marks ('), to stop bash expanding them (trying to interpret them as a special command eg. a wildcard). This is the symbol used by find to signal the end of the commands. It's usually protected by a backslash (\) or quotes to stop bash from trying to expand it. The above command commandwould find findany files fileswith the extension extension'.doc' and copycopy them to your /tmp directory,directory obviously this command commandis quite quiteuseless, it's just an example exampleof what find findcan do. Note that the quotation quotationmarks are there to stop stopbash bashfrom trying tryingto interpretinterpret the other characters charactersas something. Excluding Excludingparticular folders folderswith find can be quite quiteconfusing, but it may be necessary if you want to search searchyour main disk disk(without searching searchingevery mounted mountedfilesystem). Use the -path -path option optionto exclude excludethe particular particularfolder (note cannot have a '/' (forward slash) on the end) and the -prune -prune option optionto exclude excludethe subdirectories.subdirectories An example exampleis below:This example examplewill search searchyour entire entiredirectory directorytree (everything that is mounted mountedunder it) excluding excluding/mnt/win_c and all of the subdirectories subdirectoriesunder /mnt/win_c. When using the -path option optionyou can use wildcards.wildcardsNote that you could add addmore -path -path'/directory' statements statementson if you wanted. Find Findhas many, many different differentoptions,options refer referto the manual manual(and info) pagepage for more moredetails.details slocate slocateslocate outputs outputsa list listof all files fileson the system systemthat match matchthe pattern,pattern giving their full fullpath pathname (it doesn't have to be an exact exactmatch, anything whichwhich contains the word wordis shown). Replaces <emphasis>locate</emphasis> Secure locate is a replacement for locate, both have identical syntax. On most distributions locate is an alias to slocate. Commmand Commmandsyntax:syntax This won't work unless You need to run either updatedb (as root) or slocate -u (as root) for slocate to work. whereis whereiswhereis locates locateswhere the binary,binary source,source and manual manualpage pageis for a particular particularprogram, it uses exact exactmatches only, if you only know part partof the name use slocate. Command Commandsyntax: which whichVirtually Virtuallythe same as whereis,whereis except it only finds findsthe executableexecutable (the physical physicalprogram). It only looks looksin the PATH PATH(environment variable) of a users usersshell.shell Use the -a option optionto list listall occurances occurancesof the particular particularprogram_name program_namein your pathpath (so if theres more morethan one you can see it). Command Commandsyntax: Working with files and folders mkdir mkdirMake a directory.directory Use mkdir mkdir-p to create subdirectories subdirectoriesautomatically.automatically Directories are Folders Directories are sometimes called folders in other operating systems (such as Microsoft Windows) Examples:This would create the directories directories“work” and “maths” under matt's home homedirectory directory(if matt's home homedirectory directorydidn't exist existit would create that too).This would create a directory directoryin the current currentpath pathnamed “foo”. rm rmRemove/delete a file(s) or directories(s). You can use standard standardwildcards standard wildcardswildcardswith this command command. Command Commandsyntax:You can of course use standard standardwildcards standard wildcardswildcardsto delete deletemultiple files filesor multiplemultiple directories directoriesand files.filesUse the -R-R or -r option optionto remove removerecursively, this removes removeseverything everythingwithin subdirectories.subdirectories Also try trythe -f option optionto force forceremoval (useful when you don't want to be prompted).To remove removefiles fileswith special specialcharacters, for example,example “da*d” type:After the “--” it uses everything everythingliterally instead of using them as standard standardwildcards.standard wildcardswildcards This may be useful when you need to delete deletea filename filenamecontaining weirdweird symbols (this also works on other tools...). Disabling Aliases (per execution) On some systems such as Mandrake an alias will send rm to rm -i (prompting you for every file you wish to delete). To override this use: \rm -R directory (using the \ disables the alias for this run only) rmdir rmdirRemove an empty emptydirectory.directory If you want to remove removea directory directorywith files filesin it type “ rm rm-R -Rdirectorydirectory”, read readabove for information informationon rm rm-R-R Command Commandsyntax:This will only remove removedirectory directoryif it's empty emptyotherwise it will exit exitwith an error errormessage. mv mvMove a file fileor a directory directoryto a new newlocation or rename renamea file/directory. Rename Renameexample:example Renames Renamesfilename1 filename1to filename2.filename2To move movea file fileor directory,directory simply type: Note that this command commandcan use standard standardwildcards standard wildcardswildcards to move movefiles files(not for renaming). Move and rename Note that you can also move and rename a file in a single command. The difference is with the destination (right hand side) you change the filename to the new name of the file. For example typing: This would move the file "configuration.txt" to /home/joe/ and rename it "backupconfig" cp cpCopy Copya file.file Has a number numberof useful options,options such as -R -R(or -r) which whichrecursively recursivelycopies copiesdirectories and subdirectories.subdirectories Command Commandsyntax:Examples:Simply copy copyfile1 file1to file2 file2(in the same directory).Where the last lastoption is the directory directoryto be copy copyto. Copies Copiestwo files filesfrom different differentareas areasof the hard disk diskto /mnt/win_cThis command commandwill copy copydirectories (and all subdirectories) and/or filesfiles to new_locationnew_location Note that this command commandcan use standard standardwildcards standard wildcardswildcards to copy copymultiple files.filesYou may also like to try trythe “-u” when moving movinglarge directories directoriesaround, this copies copiesonly if the source sourcefile is newer newerthan the destination destinationto where you are copying copyingto, or if the destination file filedoes not exist existat all. ln lnCreate a link linkto a file.file There are two types typesof links:linksHard links Hard Hardlinkslinks, hard are considered pointers pointersto a file file(the number numberis listed listedby typing ls ls-l). Each hard-link hard-linkis a reference referenceto a file.fileThe file fileitself only goes away when all hard-links hard-linksare deleted.deleted If you delete deletethe original originalfile and there are hard links linksto it the original file filewill remain. Example:Will create a “hard linklink” to target_name target_namecalled link_name,link_name you need to delete deleteboth of these to removeremove the file.fileSymbolic links Symbolic Symboliclinkslinks, symbolic are created by typing “ ln ln-s”. When you remove removethe original originalfile the symbolic symboliclink linksymbolic linkbecomes broken,broken a symbolic link linkis similar similarto a windows windows“short-cut”. The advantage advantageof symbolic symboliclinks is that they can be to something on another file-system, while hard-links hard-linkscan only exist existon the same file-system.file-systemFor example:exampleThis creates a symbolic symboliclink linksymbolic linkto “target_name” called “link_name”, if you delete deletethe original originalfile the symbolic symboliclink linksymbolic linkwon't work work(it becomes a broken brokenlink). shred shredSecurely remove removea file fileby overwriting overwritingit first. Prevents Preventsthe data datafrom being recovered recoveredby software software(and even evenby most hardware), please be very careful carefulwhen using shred shredas you may never be able ableto retrieveretrieve the data datayou have run runthe application applicationon.For example:example
What this tells tellsshred,shred is to overwrite overwritethe partition partition2 times timeswith randomrandom data data(- n 2) then finish finishit up by writing writingover it with zeroes zeroes(-z) and show showyou its prog progress (-v). Of course, change change/dev/hda1 to whatever your partition partitionis. Each pass passcan take takesome time,time which whichis why I set setit to only do 2 randomrandom passes passesinstead of the default default25. You can adjust adjustthis number,number of course, to your particular particularlevel of paranoiaparanoia and the amount amountof time timeyou have.Since shred shredwrites on such a low-level,low-level it doesn't actually matter what kind kindof filesystem filesystemis on the partition--everything partition--everythingwill be unrecoverable.unrecoverable Once shred shredis finished,finished you can shut shutdown the machine machineand sell sellor throwthrow away the drive drivewith peace peaceof mind.mind...However, even evenshre dding devices devicesis not always completely reliable.reliable For example,example most disks disksmap mapout bad sectors sectorsinvisibly to the application;application if the bad sectors sectorscontain sensitiv sensitive data,data `shred' won't be able ableto destroydestroy it. [ shred shredinfo page page].This information (as quoted) has come from the “Please, For the Love of All That's Recoverable, Shred Your Hard Drive!” article, number 18 in the
Shredding files doesn't work with all filesystems Please note that as mentioned in the shred manual page (please see the manual and preferably info pages for more information). shred does not work correctly on log-structured or journaled filesystems, such as JFS, ReiserFS, XFS, Ext3 and many other modern filesystems Alternatives to using shred shred has its disadvantages when run on a filesystem. First of all since it has to be installed you cannot run shred on your operating systems filesystem, you also cannot use shred on a windows machine easily since you cannot install shred on this machine. You may like to try alternatives such as the DBAN project that create self-booting floppy disks that can completely erase a machines hard disk. You may also like to see how chattr chattrcan assist assistyou in shredding shreddingfiles filesonce they are removed (it has similar similarproblems problemsto shred,shred only ext2 ext2and ext3ext3 style filesystems...), please see .
du duDisplays information informationabout file filesize.size Use du dufilename to display displaythe size sizeof a particular particularfile. If you use it on directories directoriesit will display displaythe information informationon the sizesize of the files filesin the directory directoryand each subdirectory.subdirectory Options Optionsfor du du(use du du-option(s)):-c -- this will make du print printa grand grandtotal totalafter all arguments argumentshave being processed.processed -s -s-- summarises summarisesfor each argument argument(prints the total).-h -- prints printsthings in “ human humanreadablereadable” mode;mode for example exampleprinting printing1M (megabyte) rather ratherthan 1,024,000 (bytes).Using the -hs options optionson a directory directorywill display displaythe total totalsize sizeof the directory directoryand all subdirectories.subdirectories Command Commandsyntax:Example:This command commandwill list listthe size sizeof all files filesin the current currentdirectory directoryand it will list listthe size sizeof subdirectories,subdirectories it will list listthings in human-readablehuman-readable sizes sizesusing 1024 Kb Kbis a Megabyte,Megabyte M for megabyte,megabyte K for kilobyte kilobyteetc.file Attempts Attemptsto find findout what type of file fileit is, for example exampleit may say it's: binary,binary an image imagefile (well it will say jpeg,jpeg bmp bmpet cetera), ASCIIASCII text,text C header headerfile and many other kinds kindsof files,files it's a very useful utility.utility Command Commandsyntax:stat statTells you detailed detailedinformation informationabout a file,file including includinginode numbernumber creation/access date.date Also has many advanced advancedoptions optionsand uses. For simple use type: dd ddCopies data dataon a very low lowlevel and can be used to create copies copiesof disksdisks and many other things (for example exampleCD image imagefiles). dd can also perform performconversions on files filesand vary the block blocksize used when writing writingthe file.file Command Commandsyntax, note the block blocksize and count countare optional optionaland you can use files instead of devices... Please note dd is an advanced and difficult to use command. Its also very powerful, so be careful what you do with it Command Commandsyntax: Warning The command dd is used to work on a very low level. It can be used to overwrite important information such as your master-boot record or various important sections of your hard-disk. Please be careful when using it (especially when working with devices instead of files). touch touchThis command commandis used to create empty emptyfiles,files simply do touch touchfile_namefile_name. It is also used to update updatethe timestamps timestampson files.filestouch can be used to change changethe time timeand/or date dateof a file:fileThis particular command and explanation has been used (with editing) from the Linux Online Classroom, see [4] in the for further information.This command commandwould change changethe time timestamp stampon my_report.txtmy_report.txtroman defaultso that it wouldroman look looklike you created it at 9:15. The first four fourdigits digitsstand for May 7th (0507), in MM-DD (American style), and the last lastfour (0915) the time,time 9:15 in the morning.morning Instead of using plain plainnumbers to change changethe time,time you can use options optionssimilar to that of the date tool.tool For example:exampleYou can also use --date= instead of -d. Also have a look lookat the date datecommand under for examples exampleson using -d and --date= (the syntax syntaxfor the date datepart is exactly exactlythe same when using -d or --date). split splitSplits Splitsfiles into several severalsmaller smallerfiles. Use the -b xx option optionto split splitinto xx bytes,bytes also try try-k for kilobytes,kilobytes and -m for megabytes.megabytes You can use it to split text files and any other files... you can use cat to re-combine re-combinethe files.files This may be useful if you have to transfer transfersomething to floppy floppydisks disksor you wish to divide dividetext files filesinto certain sizes.sizes Command Commandsyntax:This will split splitthe input inputfile into 1000 lines linesof input inputeach (thats the default...), and output output(using the above example), with the input inputname file,file “fileaa” (1st part partof file), “fileab” (2nd part partof file), “fileac” (3rd part partof file) etc. until untilthe there is no more moreof the file fileleft leftto split.split
Mass Rename/copy/link ToolsThere are a few different differentways to perform performmass massrenaming of files filesin GNU/Linux (yes, mass massrenaming is possible!). There is also a perl perlscript that renames renamesthe extentions extentionson files,files see .Below are three ways to perform performmass massrenaming of files,files using the commandscommands mmv, rename (a perl perlscript) or some bash bashshell scripting.scripting   mmv mmvmmv is a mass massmove/copy/renaming tool toolthat uses standard standardwildcards standard wildcardswildcardsto performperform its functions.functionsmmv's manual manualpage pageis quite quitedifficult to understand, I have only a limited limitedunderstandi ng ngof this tool.tool However mmv supports supportssome standard standardwildcards.standard wildcardswildcardsAccording to the manual manualthe ';' wildcard wildcardis useful for matching matchingfiles filesat any depth depthin the directory directorytree (ie it will go below the current currentdirectory, recursively).An example exampleof how to use mmv mmvis shown shownbelow:The first pattern patternmatches anything with a “.JPG” and renames renameseach file file(the “#1” matches the first wildcard) to “.jpg”.Each time timeyou use a \(wildcard) you can use a #x to get that wildcard.wildcard Where x is a positive positivenumber starting startingat 1. mmv Homepage You can find mmv on the web here. Also be aware that certain options used with mmv are also applicable to other tools in the suite, these include mcp (mass copy), mad (mass append contents of source file to target name), mln (mass link to a source file). Tip: A Java alternative to mmv which runs on both GNU/Linux and Windows is available, Esomaniac rename renamerename is a perl perlscript which whichcan be used to mass massrename renamefiles according to a regular regularexpression.An example examplefor renaming renamingall “.JPG” files filesto “.jpg” is: Finding rename You can get rename from various places. I would recommend trying CPAN Search Site, I found the script here Rename Script Version 1.4 Bash  scripting scriptingBash Bashscripting is one way to rename renamefiles. You can develop developa set setof instructions instructions(a script) to rename renamefiles. Scripts Scriptsare useful if you don't have mmv or rename...One way to this is shown shownbelow:Note that the above came script scriptcame from a usenet usenetpost.post Unfortunately UnfortunatelyI do not know the author's name.The first line linesays find findeverything everythingwith the “.JPG” extension extension(capitals only, because unix unixis case sensitive).The second line lineuses basename (type man manbasename for more moredetails) with the '$i' argument.argument The '$i' is a string stringcontaining the name of the file filethat matches. The next nextportion of the line lineremoves the JPG JPGextension from the end endand adds the jpg jpgextention to each file.file The command commandmv is run runon the output.outputAn alternative alternativeis:The above script scriptrenames renamesfiles using a built-in built-inbash bashfunction. For more moreinformation informationon bash bashscripting bash scriptingyou may like to see the advanced bash scripting guide, authored authoredby Mendel MendelCooper.
Finding information about the systemtime If you are looking lookingfor how to change changethe time timeplease refer referto date here: . time timeis a utility utilityto measure measurethe amount amountof time timeit takes takesa program programto execute.execute It also measures measuresCPU CPUusage and displays statistics.statisticsUse time time-v (verbose mode) to display displayeven evenmore detailed detailedstatistics about the particularparticular program.program Example Exampleusage:/proc The files filesunder the /proc (process information informationpseudo file-system) show showvarious information informationabout the system.system Consider it a window windowto the information informationthat the kernel kerneluses. For example:example Displays information informationabout the CPU.CPU To view viewinformation informationon what kernel-modules kernel-modulesare loaded loadedon your system.systemdmesg dmesgdmesg can be used to print print(or control) the “ kernel kernelring bufferbuffer”. dmesg is generally used to print printthe contents contentsof your bootup bootupmessages displayed by the kernel.kernel This is often useful when debugging debuggingproblems.problemsSimply type: df dfDisplays information informationabout the space spaceon mounted mountedfile-systems. Use the .h .h-h option optionto have df list listthe space spacein a 'human readable' format.format ie. if there are 1024 kilobytes kilobytesleft (approximately) then df dfwill say there is 1MB 1MBleft.left Command Commandsyntax:The latter part partis optional,optional you can simply use df with or without options optionsto list listspace spaceon all file-systems.file-systems who whoDisplays information informationon which whichusers are logged loggedinto the system systemincluding the time timethey logged loggedin. Command Commandsyntax: w wDisplays information informationon who is logged loggedinto the system systemand what they are doing (ie. the processes processesthey are running). It's similar similarto who but displays slightly different differentinformation.information Command Commandsyntax:users usersVery similar similarto who except it only prints printsout the user usernames who are currently logged loggedin. (Doesn't need or take takeany options). Command Commandsyntax: last lastDisplays records recordsof when various users usershave logged loggedin or out. This includes includesinformation informationon when the computer computerwas rebooted.rebootedTo execute executethis simply type: lastlog lastlogDisplays a list listof users usersand what day/time they logged loggedinto the system.system Simply type: whoami whoamiTells the user userwho they are currently logged loggedin as. Doesn't need or take takeany options.options Simply type: free freeDisplays memory memorystatistics statistics(total, free, used, cached,cached swap). Use the -t -t option optionto display displaytotals totalsof everything everythingand use the -m -mto display displaymemory memoryin megabytes.megabytes Example:This will display displaythe memory memoryusage including includingtotals totalsin megabytes.megabytes uptime uptimePrint Printhow long longthe computer computerhas been “up”, how long longthe computer computerhas been running.running It also displays the number numberof users usersand the processor processorload (how hard the CPU has been worked...). Note: the w command commanddisplays uptime's output outputas the top topline of its output outputwhen it is executed (ie. you could use w instead...).uname unameuname is used to print printinformation informationon the system systemsuch as OS OStype, kernel kernelversionversion et cetera.ceteraSome uname options:options-a --- print printall the available availableinformation information-m --- print printonly information informationrelated to the machine machineitself. -n --- print printonly the machine machinehostname. -r --- print printthe release releasenumber of the current currentkernel.kernel -s --- print printthe operating operatingsystem systemname -p --- print printthe processor processortype. Command Commandsyntax: xargs xargsNote that xargs is an advanced,advanced confusing,confusing yet powerful powerfulcommand.command xargs is a command commandused to run runother commands commandsas many times timesas necessary, this way it prevents any kind of overload... When you run runa command commandthen | xargs xargscommand2command2. The results resultsof command1 command1will be passed passedto command2.command2 Understanding xargs tends tendsto be very difficult and my explanation explanationis not the best. Refer Referto the examples examplesbelow or try try[6] of the for another xargs tutorial.tutorial Alternatives to using xargs Please note that the below explanation of xargs is not the strongest (at the time of writing I could not find anything better :()). Alternatives may include writing a simple bash script to do the job which is not the most difficult task in the world. Examples:The first command commandis obvious, it will list listthe files filesin the current currentdirectory.directory For each line lineof output outputof ls, xargs will run rungrep on that particular particularline lineand look lookfor the string string“work”. The output outputhave the each time timegrep is executed on a new newline, the output outputwould look looklike:If grep didn't find findthe word wordthen there would be no output outputif it had an error errorthen it will output outputthe error.error Obviously this isn't very useful (you could just do grep grep*, its just an example... xargs xargsalso takes takesvarious options:options-nx --- will group groupthe first x commands commandstogether-lx --- xargs xargswill execute executethe command commandfor every x number numberof lines linesof inputinput-p --- prompt promptwhether or not to execute executethis particular particularstringstring-t --- (tell) be verbose,verbose echo echoeach command commandbefore performing performingit-i --- will use substitution substitutionsimilar similarto find's -exec -execoption,option it will executeexecute certain commands commandson something.Example:The {} would be substituted substitutedfor the current currentinput (in this example examplethe current file/directory) listed listedwithin the directory.directory The above command commandwould move moveevery file filelisted listedin dir1 dir1to dir2.dir2 Obviously this command commandwon't be too useful, it would be easier to go to dir1 dir1and type mv mv* ../dir2Here is a more moreuseful example:example This would find findall wave wavefiles fileswithin the current currentdirectory directoryand convertconvert them to mp3 mp3files files(encoded with lame) and append appenda .mp3 to the end endof the file, unfortunately it doesn't remove the .wav and so its not too useful...but it works.worksDate/Time/CalendarsThere is one command commandto change changeboth the date dateand time timeon a UNIX UNIXlike system,system date, there is also a simple calendar calendarutility, cal. If you are looking lookingto change changethe time-stamps time-stampson files filesplease see date Tells you the date date(and the time) and is also used to set setthe date/time.To set setthe date,date type date dateMM:DD:YYYY (American style styledate) where MM is month,month DD DDis the number numberof days dayswithin the month monthand YYYY YYYYis the year.yearFor example exampleto set setthe date dateto the 1st January 2000 you would type:To set setthe time time(where the -s option optionis to set seta new newtime), type:Another useful option optionyou can use is --date=“string” (or -d “string”) option optionto display displaya date datefrom x days daysago or in x days days(or x weeks,weeks months,months years yearset cetera). See the examples examplesbelow. Examples:Will print printthe date date3 months monthsand 1 day dayago from the current currentdate. Note that --date=”x month monthx day dayago” and -d -d“x month monthx day dayago” are equivalent.equivalentThe above command commandwill print printthe date date3 days daysforward forwardin time timefrom now. cal calTyping cal will give you the calendar calendarof the present presentmonth on your screen,screen in the nice nicestandard calendar calendarformat. There are various options optionsto customise customisethe calendar,calendar refer referto the info/man page.pageExample:Will display displaya calendar calendarfor a specific specificyear, simply use cal cal-y -yto printprint the calendar calendarfor the current currentyear.This will display displaythe calendar calendarfor February 2004 Finding information about partitionsThere are a number numberof ways to find findout information informationon your hard disk diskdrives, for information informationon mounted mountedpartitions also try try df dfin Using the proc  filesystem filesystemYou can look lookthrough the information informationin the relevantrelevant area areaof the proc procfilesystem,proc filesystemfilesystem under the directory directoryof either /proc/ide/ or /proc/ide?/hd? where the first question questionmark is a number numberand the second is a letter letter(starting with 'a'). For example:exampleUnder this directory directorythere will be various information informationon the hard drivedrive or cdrom cdromconnected.Using fdisk Using fdisk with the -l option optionwill output outputinformation informationon any hard drives drivesconnected connectedto the systemsystem and information informationon their partitions partitions(for example,example the type of partition). Information Informationrelating to using fdisk to partition partitionhard disks diskscan be found foundin your distributions distributionsdocumentation,documentation the fdisk manual manualpage pageor online.online Root Access Required This command needs root access to work Controlling the systemThe controlling controllingthe system systemchapter details detailscommands that you may wish to use to interact interactwith devices deviceson your system systemand then details detailshow to controlcontrol processes processesand services/daemons.eject ejecteject simply tells tellsa device deviceto open open(eject). Useful for cdrom/DVD drives.drivesFor example examplethe command commandbelow would eject ejectthe cdrom-drive cdrom-drive(if your cdromcdrom is linked linkedto /dev/cdrom): This won't work unless This will only work if the user has permission to mount the partition. Please see the tip in for more information. Mounting and Unmounting (Floppy/CDROM/Hard-drive Partitions) Allowing Users to mount partitions By default a UNIX system will allow normal users to unmount partitions. However unless given permission by the super-user, users will not be allowed to mount partitions. The commands listed below will not work for normal users unless users have permission to mount that device. If your particular distribution is setup not to allow users to mount partitions its not very hard to change this, simply edit the /etc/fstab file (as root) and: Replace the word "defaults" with "user" or Add "user" to the end of the options list for the particular partition(s). mount mountMount a device.device Attach Attachthe device deviceto the file-system file-systemhierarchy hierarchy(the tree tree( / )). This needs to be done so you can access accessthe drive drive(see below, for an example). umount umount'Unmount' a device.device The command commandumount (no 'n') unmount's a device.device It removes removesit from the file-system file-systemhierarchy hierarchy(the tree tree( / )). This needs to be done before you remove removea floppy/CDROM or any other removableremovable device device(see below, for an example).smbmount //wincomp/c /mnt/win Where “win” would be the place placeyou want it mounted mountedand “wincomp” is the IP IPaddress or name (the name will only work workif it's listed listedin /etc/hosts) of your windows windowscomputer.computer smbmount is a tool toolfrom the samba sambapackage, it can mount mounta remote remotewindows windowsfile systemsystem onto your current currentcomputer.computerUn-mounting uses the same syntax syntaxas 'umount', as listed listedabove, or you may like to use: Examples Examplesof how to mount mounta file-system:file-system mount -t ext2 /dev/fd0 /mnt/floppy mount -t iso9660 /dev/hdb /mnt/cdrom mount -t iso /tmp/image_file /mnt/iso_file/ -o loop The windows filesystem is known as vfat (standard on Windows 9x) or NFTS (standard on Windows 2000 and XP). for CDROM's This will mount an image file (usually a CD image file) so you can view/change the files (it will appear to be like any other device). The -t option On any system running a newer version of the Linux kernel the -t option is not always necessary and can be left out. Examples Examplesof how to unmount unmounta file-system file-system(necessary before you eject/remove disk):An example exampleunmount point could be “/mnt/floppy” or “/mnt/cdrom” Shutting Down/Rebooting the Systemshutdown now Shutdown Shutdownthe computer computerimmediately (don't power powerdown). Note that in UNIX UNIXsystems this kind kindof shutdown shutdownmeans to go to “ single-user single-usermodemode”. Single user usermode is a mode modewhere only the administrator administrator(root) has accessaccess to the computer,computer this mode modeis designed designedfor maintenance maintenanceand is often used for repairs.repairsFor example examplethis would take takeyou to single user usermode shutdown -h now Shutdown Shutdown(-h = halt) the computer computerimmediately. It begins the shutdown shutdownprocedure,procedure press press CTRL C CTRL-C (break-key) to stop stopit. After the end endof the command commandyou can also leave a message messagein quotationquotation marks markswhich will be broad-casted broad-castedto all users,users for example:exampleThis would halt haltthe system systemand send sendthe message messageto anyone who was loggedlogged in.Note you can put a time timeinstead of “now” or “+x minutesminutes” (any number numberof minutes minutesis appropriate) or you can set setan exact exacttime. For example exampleto shutdown shutdownat 11:50 type: Shutdown -h vs poweroff On some systems, shutdown -h and halt do not actually poweroff the system. On systems that do not power off with these commands use the poweroff command halt haltSame as above, doesn't take takeany options,options just shuts down immediately.shutdown -r now Shutdown Shutdown( -r -r= rebootreboot) the computer computerimmediately. It begins the reboot rebootprocedure,procedure press press CTRL C CTRL-C (break-key) to stop stopit. After the end endof the command commandyou can also leave a message messagein quotationquotation marks markswhich will be broad-casted broad-castedto all users,users for example:example This would reboot rebootthe system systemand send sendthe message messageto anyone who was loggedlogged in.Note you can put a time timeinstead of “now” or “+x minutesminutes” (any number numberof minutes minutesis appropriate) or you can set setan exact exacttime. For example exampleto reboot rebootat 11:50 type: reboot rebootSame as above, doesn't take takeany options,options reboots rebootsimmediately. CTRL ALT DEL CTRL-ALT-DEL (key-combination) May be used from a terminal terminalto reboot rebootor shutdown,shutdown it depends on your system systemconfiguration. Note that this doesn't work workfrom an xterminal.xterminal CTRL ALT DEL CTRL-ALT-DEL begins the reboot/shutdown immediately, the user userdoes not have to be logged loggedin. You can change the behaviour of <keycombo> <keycap>CTRL</keycap> <keycap>ALT</keycap> <keycap>DEL</keycap> </keycombo> <indexterm> <primary>CTRL-ALT-DEL</primary> </indexterm> from rebooting To disable CTRL ALT DEL CTRL-ALT-DEL from rebooting your computer (or to have it do something different), you can edit the /etc/inittab file (as root). Here is how it looks on a Mandrake/Mandriva Linux system: # Trap CTRL ALT DEL CTRL-ALT-DEL ca::ctrlaltdel:/sbin/shutdown -t3 -r now Note that the # means a comment (and is not used). If you simply put a # (hash) before the command it would disable it (it would become a comment). You could also change the command it runs for example if you changed the -r to a -h the computer would turn off instead of rebooting, or you could have it do anything you want. It's up to your creativity to make it do something interesting. Controlling Processes ps psWill give you a list listof the processes processesrunning on your system.system With no options,options ps will list listprocesses processesthat belong to the current currentuser userand have a controllingcontrolling terminal.terminal Example Exampleoptions optionsinclude:-aux --- list listall running runningprocesses processes(by all users userswith some information).-a --- list listall processes processesfrom all users.users-u --- list listmore information informationincluding user usernames, %cpu %cpuusage, and %mem %memusage et cetera.cetera-x --- list listprocesses processeswithout controlling controllingterminals.-l --- display displaydifferent information informationincluding UID UIDand nice nicevalue.value--forest --- this makes it easier to see the process processhierarchy,hierarchy which whichwill give you an indication indicationof how the various processes processeson your system systeminterrelateinterrelate (although you should also try trypstree).For example exampleto list listall running runningprocesses processeswith additional additionalinformation,information simply type: pstree pstreeDisplays the processes processesin the form formof a tree treestructure (similar to how tree does it for directories). Use the -p -p option optionto show showprocess id's.id'sExample:This would list listall processes processesand their ids.ids pgrep pgrepThis command commandis useful for finding findingthe process processid idof a particularparticular process processwhen you know part partof its name. Use the -l option optionto list listthe name of the process processas well and the -u option optionto search searchvia a particular particularuser(s).Normally pgrep will only return returnthe pid pidnumber; this way you can use it with other commands.commandsExamples:This would kill killany process processname that starts startswith mozilla.mozilla Note that this is the same as using pkill (see below).If you are unfamiliar unfamiliarwith the $( ) part partof this command,command please refer referto .To list listprocesses processesid's and names type: top topDisplays the 'top' (as in CPU CPUusage) processes,processes provides providesmore detaildetail than ps. top also provides providesan updated updateddisplay, it has many option optionthat make it fully customisable,customisable refer referto the manual manualor info infopage pagefor details.details kill To kill killprocesses processeson your system,system you will need their pid's or id'sid's . Use ps or pstree to find findout the process processid's id's(pids), or use jobs to find findout id's.id's killall and pkill - kill a process by name pkill and killall can be a lot easier to use than kill. pkill allows you to type part of the name of a process to kill it, while killall requires the full process name. See below for more information. Examples:Simply kill killa process process(allow it time timeto save saveit's files filesand exit)Same as above, except it uses an id idinstead of a pid,pid you need to use a % (percent) when using an id idto kill.kill Force Forcea process processto be killed killed(won't allow allowfiles filesto be saved savedor updated); only use when necessary because all data datathat the program programhad will be lost.lostThere are also many other kill killoptions optionssuch as kill kill-HUP-HUP (hangup)... refer referto the manual/info pages pagesfor more moreinformation.information killall killallKill a process processby it's name, uses names instead of process processid'sid's (pids). Use -v -vto have killall report reportwhether the kill killwas successful successfulor not and -i -ifor interactive interactivemode (will prompt promptyou before attempting attemptingto kill). pkill - a little like a killall with regular expressions pkill is another command that allows processes to be killed but does so using regular expressions. See below for more information. For example:exampleWould kill killanything named named“mozilla” and prompt promptyou before each kill killand report reportwhether the kill killwas successfulsuccessful or not. Unfortunately Unfortunatelyyou need to get the name exactly exactlyright for killall to work,work you would need to use “mozilla-bin” to kill killthe mozilla mozillabrowser. If you want something where you don't need to know the exact exactname try try pkill pkill(below). pkill pkillpkill is used to kill killprocesses processesaccording to an extended extendedregular regularexpression. Use the -u option optionto kill killusing a user username(s) and process processname (for example exampleto only kill killa process processof a certain user). pkill can also send sendspecific signals signalsto processes.processesFor normal normalusage simply type:Note that the “process_name” doesn't have to be an exact match...Or to kill killthe “process_name” of only the users users“fred” and “anon” type:skill skillskill is used to send senda command/username/tty a particular particularsignal.signalskill has a number numberof options optionsavailable availableto ensure ensurecorrect correctinterpretation (otherwise it just guesses guesseswhat it is), simply type skill skill-option(s)-L --- list listthe various signals signalsthat can be sent-u --- specify specifya username;username this is obviously followed followedby the user username or a space-seperated space-seperatedlist listof usernames.usernames-p --- process processid id(followed by the process processid)-c --- command commandname (this is the same as killall)-t --- (tty number)-v --- verbose verbosemode mode-i --- interactive interactivemode.skill can be used to stop,stop continue, or kill killprocesses processesusing the username,username commandcommand name or process processid id(or send sendthem any variety varietyof signals signalsyou like). Useful example:exampleThe above command commandwill stop stopall of that users usersprocesses,processes this will causecause his screen screento freeze freezeuntil untilyou type:This would tell tellthat all processes processesmay continue as before. Note that this would only work workif you are root.root Also note you can list listmore than one user username with the command commandso it will apply applyto multiple multipleusers. CTRL C CTRL-C The break breakkey,key will kill kill(break, stop) something that's runningrunning on your terminal.terminal jobs jobsPrints Printscurrently running runningjobs, as in processes processesyou have executed within the shell.shell bg bgBackgrounds Backgroundsa process.process To start starta program programin the background background(so it doesn't take takeover the terminal) use an “&” (ampersand) sign signat the end endof the command.command You usually use CTRL Z CTRL-Z to suspend suspendsomething you are currently using. You can simply use bg to resume in the background the last job suspended... Command Commandsyntax:or fg fgBring a process processto the foreground,foreground so you can interact interactwith it. The process processwill use your current currentterminal.terminal Note simply use fg to foreground the last job number suspended... You can bring jobs jobsto the foreground foregroundby name or by number number(use jobs to find findthe number). Command Commandsyntax:or nice niceSets Setsthe priority priorityfor a process.process nice nice-20 is the maximum maximumpriority priority(only administrative administrativeusers can assign assignnegative priorities), nice nice20 is the minimum minimumpriority.priority You must mustbe root rootto give a process processa higher higherpriority, but you can always lower the priority of your own processes... Example:Would execute executemake and it would run runat maximum maximumpriority.priority renice reniceChanges the priority priorityof an existing existingcommand. You may use the options options-u to change changethe priorities prioritiesof all processes processesfor a particular particularuser username and -g to change changepriorities for all processes processesof a particular particulargroup.group The default defaultis to change changevia the process processid idnumber.Example:This would change changethe priority priorityof process process2222 to +20 (minimum priority). snice snicesnice works worksvery similarly similarlyto skill, only it changes the priority priorityof the process(es). Its function functionis similar similarto that of renice.To use options options(to ensure ensurecorrect correctinterpretation) you simply type snice snice-option(s):-u --- specify specifya username;username this is obviously followed followedby the user username or a space-seperated space-seperatedlist listof usernames.usernames-p --- process processid id(followed by the process processid)-c --- command commandname (this is the same as killall)-t --- (tty number)-v --- verbose verbosemode mode-i --- interactive interactivemode.Example:This would increase increasethe priority priorityof all root's processes.processes Controlling servicesConcept Definitions   UNIX UNIXsystems use scripts scriptsto control control“daemons” which whichprovide provide“services” (for example exampleyour sound soundoutput) to run runa UNIX UNIXsystem.system UNIX UNIXsystems consist of a variety varietyof services services(daemons).A “daemon” is a system systemprocess which whichruns runsin the background background(zero interaction) performingperforming a particular particulartask.task Daemons Daemonsnormally have a “d” on the end endof their name and either listen listenfor certain events eventsor performperform a system systemtask,task for example examplesshd listens listensfor secure secureshell shellrequests to the particular particularmachine machineand handleshandles them when they occur.occur Daemons Daemonsusually perform performcritical criticalsystem tasks taskssuch as control controlswap-space, memory memorymanagement managementand various other tasks.tasks service serviceservice is a shell shellscript available availableon Mandrake/Mandriva and Redhat Redhatsystems systemswhich allows allowsyou to perform performvarious tasks taskson services.services Use the -s option optionto print printthe status statusof all services servicesavailable availableUse the -f option optionfollowed followedby a service servicename to restart restartthat particular particularservice. Use the -R option optionto restart restartall services services(note that this will kill killany current currentservices running,running including includingX).For example exampleto restart restartthe daemon daemon sshd sshdyou would type:Using the script directly You may also execute executethe shell shellscript directly from /etc/init.d. Simply go to that directory directorythen type ./script_name.Executing the script scriptshould return returnthe options optionsit can take,take by default defaultthey will be: restart restart--- this will make the service servicestop stopand then start startagain.start --- this option optionwill start starta service service(assuming its not running).stop --- this option optionwill stop stopa service service(assuming its running). status status--- this option optionwill tell tellyou about the serviceservice Managing userssu  username username(Switch User), change changeto a different differentuser.user Use su - to switch switchto root rootor su suusername, to switch switchto a different differentusername.username Using sudo Its often considered better practice to use the sudo command rather than switch to the root user The sudo command allows you to perform actions as root but logs the actions you take (so you can trace anything that was done to the system by yourself or others). sudo has a very good manual page which provides plenty of information about it. You use sudo similar to how you execute a normal command with sudo prepended to it, for example: sudo rpm -U myrpm.i386.rpm This would allow you to install a rpm even if you have the correct sudo access Note that if you want to return returnto your original originaluser useryou don't use su again, type exit or press press CTRL D CTRL-D .Simply typing su will give you some root rootprivileges,privileges but there are minor minorcomplications relating to environment environmentvariables. It's generally considered better practice practiceto use su - because it has no restrictions.restrictions root rootThe superuser.superuser This user userhas power powerover everything everythingand all, and can do anything with the system system(including destroy destroyit, and of course fix fixit :)). This user useris used to perform performmost administration administrationfunctions functionson the system.systemUsers/GroupsAll user userinformation informationis normally listed listedin the “/etc/passwd” file fileand the group groupinformation informationin the “/etc/groups” file.fileIf you need to edit editeither file fileit is recommended recommendedthat you use vipw to edit editthe password passwordfile and vigr to edit editthe group groupfile. These particular particularcommands commandstake takecare of any processing processingand locking lockingof the files filesbefore and after editing editingthem.There is a lot of information informationabout adding/removing/controlling users usersand groups,groups this information informationis only the minimal minimalinformation informationrequired. chsh chshUsed to change changeyour login loginshell.shell To list listthe shells shellsavailable availabletype:Simply type chsh chshthen [Enter], then type the name of the shell shellyou would like to use every time timeyou login.login chfn chfnChange Changefinger fingerinformation.information The information informationthis command commandchanges is reflected reflectedin the /etc/passwd file,file use this utility utilityto update updateyour real realname, office officeand home homephone numbersnumbers (if they exist). Use the -f option optionto change changea user's full fullname. Use this tool toolas either chfn or chfn chfnuser_name (usable by root rootonly). Command Commandsyntax: passwd passwdChanges the password passwordof a user.user You will need to be root rootif you want to change changeother user's passwords.passwordsSimply type passwd passwdto change changeyour own password passwordor to change changeanother user's password passwordtype: Text Related ToolsThe text textrelated tools toolschapter is the largest in this guide,guide most of the time timeon a GNU/Linux machine machineyou will spend spendtime timeinteracting with text.text This chapter briefly covers text texteditors editorsand goes into more moredepth depthon viewingviewing text,text using tools toolsto manipulate manipulatetext,text finding findingtext within files filesand changing text textformats formatsbetween windows windowsbased systems systemsand GNU/Linux based systems.Text Editors vi viA traditional traditionalUNIX UNIXsystem systemtext editor,editor should be on any UNIX UNIXsystem. It is fairly difficult to learn learnbut quite quitepowerful, it is also quite quitesmall and uses minimal minimalamounts of resources.resources vim vim - vi improved. A newer version of the vulnerable vi editor. Many systems use vim rather than vi. emacs emacsMore than just a text texteditor.editor This text texteditor editorhas a steep steeplearning learningcurve but is also very powerful,powerful it is both advanced advancedand quite quitelarge. Emacs Emacscan do anything, surf surfthe internet,internet chat,chat play playgames and many other tasks.tasksOthers There are too many different differenttext texteditors editorsto list listhere. Have a look lookon the internet,internet either search searchfor them you will find findmany of them at Sourceforge or Freshmeat. Text Viewing Tools head headWith no options optionsit shows showsthe first ten tenlines linesof a text textfile. Use head head-n -nx (where “x” is a number) to display displaythe first x lines. Try Try head head-F -Fto use a continually updated updatedversion versionof head (if the file filechanges it will be reloaded reloadedand displayed), please note that using this option optionwill run runhead is a continuous continuousloop so you'll need to use CTRL C CTRL-C to exit.exitFor example:exampleWill display displaythe top top20 entries entriesof the file file“somelog.txt”. tail tailWith no options optionsit shows showsthe last lastten lines linesof a file.file Use tail tail-n -nx (where “x” is a number) to display displaythe last lastx lines. Try Try tail tail-F -Fto use a continually updated updatedversion versionof tail (if the file filechanges it will be reloaded reloadedand displayed), please note that using this option optionwill run runtail is a continuous continuousloop so you'll need to use CTRL C CTRL-C to exit.exitFor example:exampleWill display displaythe last last20 entries entriesof the file file“somelog.txt”. less lessViews text,text can scroll scrollbackwards and forwards.forwards Has many different differentoptions optionswhich are all described describedin the manual manualpage.page When less lessis already running,running use :n and :p (type a colon colonthen the character) to move moveto the next nextand previous previousfiles (when there are multiple multipleopen openfiles). Command Commandsyntax:Or using a tool tool(in this example examplecat):more Displays text,text one page pagefull at a time,time more morelimited than less. In this case less is better than more.Or using a tool tool(is this example examplecat):cat Combines Combines(concatenates) multiple multipledocuments documentsinto one document.document Can be used on individual individualfiles filesas well.Some useful options:options-b --- number numberall non-blank non-blanklineslines-n --- number numberall lines.lines Also try tryusing nl to number numberlines lines(it can do more morecomplex complexnumbering), find findit under under this section,section Example: wholefile.txt ]]>Would combine combine(concatenate) filepart1,filepart1 filepart2 filepart2and filepart3 filepart3into the single file file“wholefile.txt”. tac tacCombines (concatenates) multiple multipledocuments documentsinto one document documentand outputsoutputs them in reverse.reverse Can also be used on individual individualfiles.files Notice that tac is cat written writtenbackwards. Example: wholefile.txt ]]>Would combine combine(concatenate) filepart1,filepart1 filepart2 filepart2and filepart3 filepart3into the single file filebut have each of the files fileswritten writtenin reverse.reversez* commands Many commands commandscan be prefixed prefixedwith a “z” to read/work within a gzip gzipcompressed file.file Some examples examplesare zcat, zless,zless zmore,zmore zgrep,zgrep zcmp,zcmp zdiffzdiff. There are many utilities utilitiesfor working workingwith text textwithin compressed compressedfiles fileswithout trying to manually de-compress them somewhere first...most begin with a “z”. bz* commands There are also a few commands commandsthat prefixed prefixedwith a “bz” to read/work within a file filecompressed compressedwith bzip2.bzip2 The tools toolsare bzcat, bzless,bzless bzgrepbzgrep Text Information Tools wc wcWord Wordcount, count counthow many words wordsyou have in a text textdocument. Can also be used to count countthe lines linesor bytes byteswithin the file.file Use the options options -w -wfor words,words -l for lines linesand -c for bytes.bytes Or simply run runwc with no options optionsto get all three. Command Commandsyntax: style styleTo run runvarious readability readabilitytests on a particular particulartext textfile. Will output outputscores scoreson a number numberof different differentreadability readabilitytests (with no options). Command Commandsyntax: Find style in the diction package This command is part of the diction package and does not appear to be used too often these days cmp cmpDetermines whether or not two files filesdiffer, works workson any type of file.file Very similar similarto diff only it compares compareson the binary binarylevel instead of just the text.text diff diffCompares two text textfiles filesand output outputa difference differencereport (sometimes called a "diff"diff) containing the text textthat differs between two files.files Can be used to create a 'patch' file file(which can be used by patch). Example:diff will output outputa '>' (followed by the line) for each line linethat isn't in the first file filebut is in the second file, and it will output outputa '<' (followed by the line) for each line linethat is in the first file filebut not in the second file.filesdiff sdiffInstead of giving a difference differencereport, it outputs outputsthe files filesin two columns,columns side sideby side, separated separatedby spaces.spaces diff3 diff3Same as diff except for three files.files   comm commCompares two files,files line-by-line line-by-lineand prints printslines linesthat are unique uniqueto file1 file1(1st column), unique uniqueto file file2 (2nd column) and common commonto both filesfiles (3rd column). Use comm with the -1, -2, or -3 to suppress suppressthe printing printingof those particular particularlines.lines Simply run runcomm to have all three listed listed(ie. unique uniqueto files files1 and 2 and common commonto both). Command Commandsyntax: look lookTo output outputa list listof words wordsin the system systemdictionary that begin with a given string string-- this is useful for finding findingwords wordsthat begin with a particularparticular phrase phraseor prefix.prefix Give the string stringas an argument;argument it is not case sensitive.sensitive Command Commandsyntax: Text manipulation tools Also see Also see tac, and cat over in this section, , as they can perform text modification too sort Sorting Sortingtext with no options optionsthe sort sortis alphabetical.alphabetical Can be run runon text textfiles filesto sort sortthem alphabetically alphabetically(note it also concatenatesconcatenates files), can also be used with a pipe pipe'|' to sort sortthe output outputof a command.command Use sort sort-r-r to reverse reversethe sort sortoutput,output use the -g -g option optionto sort sort'numerically' (ie read readthe entire entirenumber,number not just the first digit).Examples:The above command commandwould run runcat on the shopping shoppinglist listthen sort sortthe results resultsand display displaythem in alphabeticalalphabetical order.orderThe above command commandwould run runsort on a file fileand sort the file filein reverse reversealphabetical alphabeticalorder. medskipAdvanced sort sortcommands:commands sort is a powerful powerfulutility,utility here are some of the more morehard to learn learn(and lesserlesser used) commands.commands Use the -t option optionto use a particular particularsymbol symbolas the separator separatorthen use the -k option optionto specify specifywhich column columnyou would like to sort sortby, where column 1 is the first column columnbefore the separator.separator Also use the -g option optionif numeric numericsorting is not working workingcorrectly (without the -g -goption sort sortjust looks looksat the first digit digitof the number). Here is a complex complexexample:exampleThis will sort sortthe “/etc/passwd” file,file using the colon colon':' as the separator.separator It will sort sortvia the 4th column column(GID section,section in the file) and then sort within that sort sortusing the first (name) if there are any ties.ties The -g is there so it sorts via full fullnumbers, otherwise it will have 4000 before 50 (it will just look at the first digit...). join joinWill put two lines linestogether assuming they share shareat least leastone commoncommon value valueon the relevant relevantline. It won't print printlines if they don't have a common commonvalue.value Command Commandsyntax: cut cutPrints Printsselected selectedparts of lines lines(of a text textfile), or, in other words,words removes removescertain sections sectionsof lines.lines You may wish to remove removethings according to tabs tabsor commas,commas or anything else you can think of... Options Optionsfor cut: -d -d--- allows allowsyou to specify specifyanother delimiter,delimiter for example example':' is often used with /etc/passwd: -f -f--- this option optionworks workswith the text textby columns,columns separated separatedaccording to the delimiter.delimiter For example exampleif your file filehad lines lineslike “result,somethingelse,somethingelse” and you only wanted result resultyou would use:This would get you only the usernames usernamesin /etc/passwd“,” (commas) --- used to separate separatenumbers, these allow allowyou to cut cutparticularparticular columns.columns For example:exampleThis would only show showthe username usernameand the shell shellthat each person personis setupsetup for in /etc/passwd.“-” (hyphen) --- used to show showfrom line linex to line liney, for example example1-4, (would be from lines lines1 to line line4).This would cut cut(display) characters characters(columns) 1 to 50 of each line line(and anything else on that line lineis ignored) -x -x--- where x is a number numberto cut cutfrom line line1 to “x” and use x- (where x is a number) to cut cutfrom “x” to the end.endThis would display display(“cut”) characters characters(columns) 1 to 5, 8 and from 20 to the end.endispell/aspell To spell spellcheck a file fileinteractively, prompts promptsfor you to replacereplace word wordor continue. aspell is said to be better at suggesting suggestingreplacement words,words but its probablyprobably best to find findout for yourself.aspell example:exampleThis will run runaspell on a particular particularfile called “FILE.txt”, apsell will run runinteractively and prompt promptfor user userinput.ispell example:exampleThis will run runispell on a particular particularfile called “FILE.txt” ispell will run runinteractively and prompt promptfor user userinput. chcase chcaseIs used to change changethe uppercase uppercaseletters in a file filename to lowercaselowercase (or vice versa).You could also use tr to do the same thing... newFileName.txt ]]>The above would convert convertuppercase uppercaseto lowercase lowercaseusing the the file file“fileName.txt” as input inputand outputting the results resultsto “newFileName.txt”. newFileName.txt ]]>The above would convert convertlowercase to uppercase uppercaseusing the the file file“fileName.txt” as input inputand outputting the results resultsto “newFileName.txt”.chcase (a perl perlscript) can be found foundat the chcase homepage. fmt fmt(format) a simple text textformatter. Use fmt fmtwith the -u option optionto output outputtext with "uniform spacing", where the space spacebetween wordswords is reduced reducedto one space spacecharacter characterand the space spacebetween sentences sentencesis reduced to two space spacecharacters. Example:Will make sure the amount amountof space spacebetween sentences sentencesis two spaces spacesand the amount amountof space spacebetween words wordsis one space. paste pastePuts lines linesfrom two files filestogether, either lines linesof each file fileside by side side(normally separated separatedby a tab-stop tab-stopbut you can have any symbols(s) you like...) or it can have words wordsfrom each file file(the first file filethen the second file) side sideby side.To obtain a list listof words wordsside by side,side the first word wordfrom the first filefile on the left leftside separated separatedby a tab-stop tab-stopthen the first word wordfrom the second file fileyou would type:To have the list listdisplayed in serial,serial first word wordfrom first file,file [Tab], second word wordfrom first file,file then third and fourth fourthuntil untilthe end endof the first file filetype: expand expandWill convert converttabs to spaces spacesand output outputit. Use the option option -t -tnum to specify specifythe size sizeof a “tapstop”, the number numberof characters charactersbetween each tab.tab Command Commandsyntax: unexpand unexpandWill convert convertspaces to tabs tabsand output outputit. Command Commandsyntax: uniq uniqEliminates duplicate duplicateentries from a file fileand it sometimes greatly greatlysimplifies the display.display uniq options:options -c --- count countthe number numberof occurances occurancesof each duplicateduplicate -u -u--- list listonly unique uniqueentries -d -d--- list listonly duplicate duplicateentriesFor example:exampleThis would display displayany duplicate duplicateentries only and a count countof the numbernumber of times timesthat entry entryhas appeared. tr tr(translation). A filter filteruseful to replace replaceall instances instancesof characters charactersin a text textfile or "squeeze"squeeze the white whitespace.Example: new_file ]]>This will run runthe cat program programon some file,file the output outputof this command commandwill be sent to the tr command,command tr will replace replaceall the instances instancesof 3 with 5, like a search searchand replace. You can also do other things such as: new_file ]]>This will run runcat on some_file some_fileand convert convertany capital capitalletters to lowercase lowercaseletters (you could use this to change the case of file names too...). Alternatives You can also do a search and replace with a one line Perl command, read about it at the end of this section. nl nlThe number numberlines linestool,tool it's default defaultaction actionis to write writeit's input input(either the file filenames given as an argument,argument or the standard standardinput) to the standard output.output Line Linenumbers are added to every line lineand the text textis indented.indented This command commandcan do take takesome more moreadvanced advancednumbering numberingoptions, simply readread the info infopage pageon it. These advanced advancedoptions optionsmainly relate to customisation customisationof the numbering,numbering including includingdifferent forms formsof separation separationfor sections/pages/footers etc.Also try try cat cat-n-n (number all lines) or cat cat-b (number all non-blank non-blanklines). For more moreinfo infoon cat check checkunder this section:section There are two ways you can use nl:The above command commandwould add addnumbers to each line lineof some_text_file.some_text_file You could use nl to number numberthe output outputof something as shown shownin the example examplebelow;Perl search and replace  text textTo search searchand replace replacetext in a file fileis to use the following followingone-line one-linePerl commandcommandThis information has been taken from the Linux Cookbook (without editing). See [3] in the for further information.:romanIn this example,example defaultoldstringroman is the string stringto search,search defaultnewstringroman is the string stringto replace replaceit with, and defaultfilespecroman is the name of the file fileor files filesto work workon. You can use this for more morethan one file.file Example: romanTo replace replacethe string string`helpless' with the string string`helpful' in all filesfiles in the current currentdirectory,directory type: romanAlso try tryusing tr to do the same thing (see further above in this section). If these tools are too primitive If these text tools are too simple for your purposes then you are probably looking at doing some programming or scripting. If you would like more information on bash scripting then please see the advanced bash scripting guide, authored by Mendel Cooper. sed and awk are traditional UNIX system tools for working with text, this guide does not provide an explanation of them. sed works on a line-by-line basis performing substitution and awk can perform a similar task or assist by working on a file and printing out certain information (its a programming language). You will normally find them installed on your GNU/Linux system and will find many tutorials all over the internet, feel free to look them up if you ever have to perform many similar operations on a text file. Text Conversion/Filter ToolsFilters (UNIX System/dos formats) The following followingfilters filtersallow you to change changetext from Dos-style Dos-styleto UNIX UNIXsystemsystem style styleand vice-versa,vice-versa or convert converta file fileto other formats.formats Also note that many modern text editors can do this for you...Why use filters? Because UNIX UNIXsystems and Microsoft Microsoftuse two different differentstandardsstandards to represent representthe end-of-line end-of-linein an ASCII ASCIItext file.file This can sometimes causes causesproblems problemsin editors editorsor viewers viewerswhich aren't familiarfamiliar with the other operating operatingsystems systemsend-of-line end-of-linestyle. The following followingtools toolsallow you to get around this difference.differenceWhats the difference? The difference differenceis very simple, on a Windows Windowstext file,file a newline newlineis signalled signalledby a carriage carriagereturn returnfollowed by a newline, '\r\n' in ASCII.ASCIIOn a UNIX UNIXsystem systema newline newlineis simply a newline, '\n' in ASCII.ASCII dos2unix dos2unixThis converts convertsMicrosoft-style end-of-line end-of-linecharacters to UNIX UNIXsystemsystem style styleend endof line linecharacters. Simply type: fromdos fromdosThis does the same as dos2unix dos2unix(above). Simply type:fromdos can be obtained from the from/to dos website. unix2dos unix2dosThis converts convertsUNIX system systemstyle end endof line linecharacters to Microsoft-sty le leend-of-line characters.characters Simply type: todos todosThis does the same as unix2dos (above). Simply type:todos can be obtained from the from/to dos website. antiword antiwordThis filter filterconverts convertsMicrosoft word worddocuments into plain plainASCII text textdocuments.documents Simply type:You can get antiword from the antiword homepage. recode recodeConverts Convertstext files filesbetween various formats formatsincluding HTML HTMLand dozensdozens of different differentforms of text textencodings.encodings Use recode recode-l for a full fulllisting.listing It can also be used to convert converttext to and from Windows Windowsand UNIX UNIXsystemsystem formats formats(so you don't get the weird weirdsymbols). Warning By default recode overwrites the input file, use '<' to use recode as a filter only (and to not overwrite the file). Examples:   UNIX UNIXsystem systemtext to Windows Windowstext: Windows Windowstext to UNIX UNIXsystem systemtext: UNIX UNIXsystem systemText to Windows WindowsText without overwriting overwritingthe original originalfile (and creating a new newoutput file): recoded_file ]]> tr tr(Windows to UNIX UNIXsystem systemstyle conversion conversiononly). While tr is not specifically specificallydesigned to convert convertfiles filesfrom Windows-format Windows-formatto UNIXUNIX system systemformat formatby doing: outputFile.txt ]]>The -d -dswitch means to simply delete deleteany occurances occurancesof the string.string Since we are looking lookingfor '\r', carriage carriagereturns returnsit will remove removeany it finds,finds making the file filea UNIXUNIX system text file...Conversion tools enscript enscriptConverts Convertstext files filesto postscript,postscript rtf,rtf HTML HTML(use ghostview to view viewthe postscript postscriptfile). enscript has a large number numberof options optionswhich can be used to customise customisethe output.outputExamples:These examples are based off information from the enscript manual page, see [12] in the for further information. This will take takesome file fileand output outputit as a html htmlfile. Display Displayhelp on using the highlight highlightfeature (list all different differenttypes typesof highlighting highlightingavailable) Highlight Highlightusing the lang lang(pretty print), example:example Add Addall the files fileswith a .h .hand a .c (C source sourceand header headerfiles) into a filefile called foo.foohtml, use colour colourand add adda table tableof contentscontentsFor further options optionsrefer to the well written writtenmanual page pageof enscript.enscript figlet figletUsed to create ASCII ASCII“art”. Figlet Figletcan create several severaldifferent differentforms (fonts) of ASCII ASCIIart,art its one of the more moreunusual unusualprograms programsaround. Finding Text Within Files grep grepLooks for text textwithin files.files For example:example Example Exampleoptions:options-v --- this option optionis used to display displaylines lineswhich do not contain the string.string-n --- this option optiondisplays the line linenumbers-w --- this option optionmakes grep grepmatch the whole word word-A x or -B x (where x is a number) --- display display“x” lines linesAfter or Before the section sectionwhere the particular particularword wordis found.found -r or rgrep --- search searchfor text textwithin files filesrecursively. This command commanduses regular regularexpressions, for more moreinformation informationplease see, .For example,example this command commandwould look lookin the file file“rpmlist.txt” for anything starting startingwith “rpm”:Or you could use it like this, to search searchthrough the output outputof another file:fileThe first command commandlists listsall RPM's installed installedon your system,system the second findsfinds any containing the string string“ogg” and outputs outputsthem. rgrep rgrepA "recursive"recursive version versionof grep (this is a different differentprogram to grep). This will search searchall the files filesin the current currentdirectory directoryand all it's subdirectories and print printthe names of the files filesand the matching matchingline.line Follows Followssimilar syntax syntaxto grep (see above). You could also use grep with the -r option optionto achieve the same affect.affect fgrep fgrepThis version versionof grep calls callsgrep with the -F option.option This will look lookfor literal literalstrings only, it won't use or expand expandany kindkind of regular regularexpression.For example exampleyou could type:And fgrep would look lookfor the string string“a$*b?” in the file file“file.txt”. Other Versions There are various versions of grep which are designed to do different things try searching for them on the internet or within your distribution. Mathematical tools num-utils homepage The “num-utils” homepage, Num Utils, contains a variety of command line programs that could be useful when performing maths on your GNU/Linux machine. units unitsConvert Convertunits of measurement measurementbetween different differentscales.scales For example,example centimeters centimetersto inches,inches litres litresto gallons.gallonsSimply run runthe program,program I recommend recommendrunning runningit as follows:followsThis will run runthe program programand it will tell tellyou exactly exactlywhat it is doing.Example: you enter enter“60 metersmeters” then you want it worked out in “kilometers”. The first line linewill tell tellyou what this evaluates evaluatesto.If you wanted the conversion conversionrate for “meters” to “kilometers” read readthe second line lineof the output output(which will tell tellyou meters/1000).Note: press press CTRL D CTRL-D (end-of-file key) when you are finished finishedusing units. python pythonPython Pythonis a very powerful,powerful easy to learn,learn general generalpurpose, interpretedinterpreted programming programminglanguage. .h .hand it makes a great greatcalculator! If you don't have a calculator calculatorinstalledinstalled then simply type python, then hit hit[Enter]. This will execute executethe Python Pythoninterpreter in interactive interactivemode. Type your sums sumsjust like you would use a calculator.calculator Note that if you want to work workout fractions fractionsmake sure you use a decimaldecimal point and a zero zeroto obtain the correct correctanswer (otherwise it will use integerinteger division).To start startpython in interactive interactivemode, simply type:Once python pythonis started startedyou can use it to add addup sums sumsor maybe do some python programming.programmingUse CTRL D CTRL-D (end-of-file key) to exit exitthe Python Pythoninterpreter. numgrep numgrepA little bit bitlike grep greponly this is designed designedfor numbers numbersonly. Use '/' (forward slashes) to contain each expression.expression Use m<n> to find findmultiples of the number numbern and use f<n> to find findfactorsfactors of the number numbern. Use commas commasto seperate expressions expressionsand .. (two dots) to represent representa range.range For example,example to input inputfrom standard standardinput inputstandard inputyou could simply type:To input inputfrom a file fileand look lookfor numbers numbersbetween 1 and 1000 you could type: This tool comes from the num-utils package Please note that this tool is part of the num-utils package. Network CommandsThe network networkcommands chapter explains explainsvarious tools toolswhich can be useful when networking networkingwith other computers computersboth within the network networkand accross the internet,internet obtaining more moreinformation informationabout other computers.computers This chapter also includes includesinformation informationon tools toolsfor network networkconfiguration, file filetransfer transferand working workingwith remote remotemachines.machines netstat netstatDisplays contents contentsof /proc/net files.files It works workswith the Linux LinuxNetwork Subsystem,Subsystem it will tell tellyou what the statusstatus of ports portsare ie. open,open closed,closed waiting,waiting masquerade masqueradeconnections. It will also display displayvarious other things. It has many different differentoptions.options tcpdump tcpdumpThis is a sniffer,sniffer a program programthat captures capturespackets off offa networknetwork interface interfaceand interprets interpretsthem for you. It understands all basic basicInternet Internetprotocols,protocols and can be used to save saveentireentire packets packetsfor later inspection.inspectionping The ping pingcommand command(named after the sound soundof an active activesonar system) sends sendsecho requests requeststo the host hostyou specify specifyon the command commandline, and listslists the responses responsesreceived receivedtheir round roundtrip time.time You simply use ping pingas:The host hostname will work workif the IP IPaddress is listed listedin “/etc/hosts” (if it's within your network) or if your on the internet internetit will use the DNS DNSsystem. Note to stop stopping (otherwise it goes forever) use CTRL C CTRL-C (break). hostname hostnameTells the user userthe host hostname of the computer computerthey are logged loggedinto. Note: may be called host. traceroute traceroutetraceroute will show showthe route routeof a packet.packet It attempts attemptsto list listthe series seriesof hosts hoststhrough which whichyour packets packetstraveltravel on their way to a given destination.destination Also have a look lookat xtraceroute (one of several severalgraphical graphicalequivalents of this program). Command Commandsyntax:tracepath tracepathtracepath performs performsa very simlar function functionto traceroute the main difference differenceis that tracepath doesn't take takecomplicated complicatedoptions. Command Commandsyntax: findsmb findsmbfindsmb is used to list listinfo infoabout machines machinesthat respond respondto SMB SMBname queries queries(eg. windows windowsbased machines machinessharing sharingtheir hard disk's). Command Commandsyntax:This would find findall machines machinespossible,possible you may need to specify specifya particularparticular subnet to query those machines only... nmap nmap“ network networkexploration tool tooland security securityscannerscanner”. nmap is a very advanced advancednetwork networktool toolused to query querymachines (local or remote) as to whether they are up and what ports portsare open openon these machines.machines A simple usage usageexample:exampleThis would query queryyour own machine machineas to what ports portsit keeps open.open nmap is a very powerful powerfultool,tool documentation documentationis available availableon the nmap site as well as the information informationin the manual manualpage.pageNetwork Configuration ifconfig ifconfigThis command commandis used to configure configurenetwork networkinterfaces, or to displaydisplay their current currentconfiguration.configuration In addition additionto activating activatingand deactivating deactivatinginterfaces interfaceswith the “up” and “down” settings,settings this command commandis necessary for setting settingan interface's addressaddress information informationif you don't have the ifcfg script.scriptUse ifconfig as either:This will simply list listall information informationon all network networkdevices currently up.This will take takeeth0 (assuming the device deviceexists) down, it won't be ableable to receive receiveor send sendanything until untilyou put it “up” again.Clearly there are a lot more morecommands commandsfor this tool,tool you will need to readread the manual/info page pageto learn learnmore moreabout them. ifup ifupUse ifup ifupdevice-name to bring an interface interfaceup by following followinga script script(which will contain your default defaultnetworking networkingsettings). Simply type ifup ifupand you will get help helpon using the script.scriptFor example exampletyping:Will bring eth0 eth0up if it is currently down. ifdown ifdownUse ifdown ifdowndevice-name to bring an interface interfacedown using a script script(which will contain your defaultdefault network networksettings). Simply type ifdown ifdownand you will get help helpon using the script.scriptFor example exampletyping:Will bring eth0 eth0down if it is currently up. ifcfg ifcfgUse ifcfg to configure configurea particular particularinterface.interface Simply type ifcfg ifcfgto get help helpon using this script.scriptFor example,example to change changeeth0 eth0from 192.168.0.1 192.168.0.1to 192.168.0.2 192.168.0.2you could do:The first command commandtakes eth0 eth0down and removes removesthat stored storedIP IPaddress and the second one brings it back up with the new newaddress. route routeThe route command commandis the tool toolused to display displayor modify modifythe routing routingtable.table To add adda gateway gatewayas the default defaultyou would type: Internet Specific CommandsNote that should DNS DNSnot be configured correctly correctlyon your machine,machine you need to edit edit“/etc/resolv.conf” to make things work... host hostPerforms a simple lookup lookupof an internet internetaddress (using the Domain DomainName System,System DNS). Simply type:or dig digThe "domain information informationgroper" tool.tool More advanced advancedthen host... Give a host-name host-nameas an argument argumentto output outputinformation informationabout that host,host including includingit's IP IPaddress, hostname hostnameand various other information.information For example,example to look lookup information informationabout “www.amazon.com” type:To find findthe host hostname for a given IP IPaddress (ie a reverse reverselookup), use dig with the `-x' option.optionThis will look lookup the address address(which may or may not exist) and returns returnsthe address addressof the host,host for example exampleif that was the address addressof http:http//slashdot.org then it would return return“http://slashdot.org”.dig takes takesa huge hugenumber numberof options options(at the point of being too many), referrefer to the manual manualpage pagefor more moreinformation.information whois whois(now BW whois) is used to look lookup the contact contactinformation informationfrom the “whois” databases,databases the servers serversare only likely to hold major majorsites. Note that contact contactinformation informationis likely to be hidden hiddenor restricted restrictedas it is often abused abusedby crackers crackersand others looking lookingfor a way to cause causemalicious damage damageto organisation's. wget wget(GNU Web Webget) used to download downloadfiles from the World WorldWide Web.To archive archivea single web website, use the -m or --mirror (mirror) option.optionUse the -nc -nc(no clobber) option optionto stop stopwget from overwriting overwritinga file fileif you already have it.Use the -c or --continue option optionto continue a file filethat was unfinished unfinishedby wget wgetor another program.programSimple usage usageexample:exampleThis would simply get a file filefrom a site.site wget can also retrieve retrievemultiple files filesusing standard standardwildcards,standard wildcardswildcards the same as the type used in bash,bash like *, [ ], ?. Simply use wget as per normal normalbut use single quotation quotationmarks (' ') on the URL URLto preventprevent bash bashfrom expanding expandingthe wildcards.wildcards There are complications if you are retrieving from a http site (see below...).Advanced usage usageexample,example (used from wget manual manualpage):This will parse parsethe file filebookmarks.html bookmarks.htmland check checkthat all the links linksexist.existAdvanced usage;usage this is how you can download downloadmultiple files filesusing http http(using a wildcard...).Notes: http httpdoesn't support supportdownloading downloadingusing standard standardwildcards,standard wildcardswildcards ftp ftpdoes so you may use wildcards wildcardswith ftp ftpand it will work workfine. A work-around work-aroundfor this http httplimitation is shown shownbelow:This way around the wildcard limitation has been adopted (with a tiny amount of editing) from wget manual page, see [9] in the for further information.This will download download(recursively), to a depth depthof one, in other words wordsin the current currentdirectory directoryand not below that. This command commandwill ignore ignorereferences referencesto the parent parentdirectory,directory and downloadsdownloads anything that ends endsin “.gif”. If you wanted to download downloadsay, anything that ends endswith “.pdf” as well than add adda -A.pdf before the website websiteaddress. Simply change changethe website websiteaddress and the type of file filebeing downloadeddownloaded to download downloadsomething else. Note that doing -A.gif is the same as doing -A “*.gif” (double quotes quotesonly, single quotes quoteswill not work).wget has many more moreoptions optionsrefer to the examples examplessection of the manual manualpage,page this tool toolis very well documented. Alternative website downloaders You may like to try alternatives like httrack. A full GUI website downloader written in python and available for GNU/Linux curl curlcurl is another remote remotedownloader.downloader This remote remotedownloader downloaderis designed designedto work workwithout user userinteraction and supports supportsa variety varietyof protocols,protocols can upload/download and has a large numbernumber of tricks/work-arounds for various things. It can access accessdictionary dictionaryservers servers(dict), ldap ldapservers, ftp,ftp http,http gopher,gopher see the manual manualpage pagefor full fulldetails.details To access accessthe full fullmanual manual(which is huge) for this command commandtype:For general generalusage you can use it like wget. You can also login loginusing a user username by using the -u option optionand typing your username usernameand password passwordlike this:To upload uploadusing ftp ftpyou the -T option:optionTo continue a file fileuse the -C option:option Remote Administration Related ssh sshSecure Secureshell,shell remotely remotelylogin loginon a machine machinerunning runningthe sshd daemon.daemon Once you are logged loggedin you have a secure secureshell shelland are able ableto executeexecute various commands commandson that computer computersuch as copy copyfiles, shut shutit down, just like it was your own GNU/Linux PC.PCOr you can use ssh with a full fullhostname hostnameto connect connectto a remote remotemachine machine(as in across the internet). Examples: Connect Connectto a remote remotesystem systemwith your current currentuser username, you will obviously need the password passwordof the user useron the other machine.machine Connect Connectto a remote remotesystem systemwith your a different differentuser username, you will obviously need the password passwordof the user useron the other machine.machine scp scpSecure Securecopy,copy part partof the ssh sshpackage.package Allows Allowsyou to copy copyfiles from one computer computerto another computer, use -r -rto copy copyrecursively (copy entire entiredirectories directoriesand subdirectories).scp's syntax syntaxis alwaysWhere either machine machinecan be a local localdirectory directory(on the current currentfilesystemfilesystem /) or a remote remotemachine.machine Remote Remotemachines machinesare usually machinesFullName:/directory (if you omit omitthe directory directorypart it will just assume the home homedirectory of the username usernameyou are logging loggingin with).The example examplebelow copies copiesall files filesfrom the current currentdirectory directory(not includingincluding any directories), the command commandwill login loginto “new” using the username usernameof the person personcurrently logged loggedin on the local localcomputer,computer the files fileswill be copied to the root rootdirectory directoryof the remote remotecomputer computercalled “new” (which is probably probablyon the LAN):You could also copy copyfiles from another computer computerto another computer. Let's say you are on a computer computercalled “p100”. And you want to copy copyfiles (and directories) from “hp166” (in the /tmp directory directoryand anything below that) to “new” and put the files filesin new's tempory temporydirectory.directory You could do:Assuming you were logged loggedin as “fred” you would need passwords passwordsfor user user“fred” on the computers computershp166 and new.new Add Addan user_name@ before the computer computername to login loginunder a different differentuser username. For example exampleto perform performthe above command commandwith user user“root” on hp166 hp166and “anon” on new newyou would type:To copy copyfrom a remote remotemachine machineto a local localcomputer computeryou simply do things in reverse:reverseThis will copy copyfiles on the remote remotemachine machinein the directory directory“mystuff” to your local localcomputer.computer Remote Machines Please note that when working with a remote machine you need to have a : (colon) after the machine name even if you want the files in their home directory. Otherwise the command will fail. sftp sftpSecure ftp,ftp another part partof the ssh sshpackage.package This command commandis similar similarto ftp ftpbut uses an encrypted encryptedtunnel tunnelto connectconnect to an ftp ftpserver serverand is therefore more moresecure securethan just plain plainftp.The command commandusage is very similar similarto ftp (the command-line command-linetool), sftp (once running) uses commands commandssuch as help help(for help), put (send files filesto the server), get (download files filesfrom the server) and various others, refer referto the manualmanual page pageand internal internaldocumentation documentationfor further details.details Graphical programs Sometimes its easier to manage files with a GUI, many of these programs do have good GUI equivalents, try searching the internet or sites like Sourceforge or Freshmeat. SecurityThe security securitychapter is designed designedto give the user usera very basic basiclevel levelof understanding of security securitywithin the GNU/Linux operating operatingsystem.system This chapter also has information informationon the UNIX UNIXsystem systemstyle file filepermissionspermissions used on most GNU/Linux machines.machines More comprehensive comprehensiveguides can be found foundat the Linux Documentation Project, such as the Linux Security howto authored authoredby Kevin Fenzi Kevin Fenziand Dave Wreski.Dave Wreski medskipThere are also sites sitessuch as Linux Security. If your looking lookingfor a program programto assist assistin locking lockingdown your operatingoperating system systemyou may want to check checkBastille Linux that runs runson RPM RPMbased distributions distributions(Redhat/Mandriva/SuSE).Changing root's  password passwordThis trick trickworks workswell if you have forgotten forgottenyour superuser superuserpassword, type linux linuxsingle at a LILO/Grub prompt.prompt Then passwd once the system systemhas started startedand you are at a console.console Grub: If you are using grub grubgo to the relevant relevantline (the one with the kernelkernel and various options) then press press'e' for edit editand add add“single” on to the end endof the section sectionthat boots bootsthe kernel.kernel Then hit hit[Enter] and press press'b' (to boot). Lilo: If you are using lilo lilopress escape escapeand type “ linux linuxsingle” and then hit hit[Enter] to boot.boot Security Warning This is also a basic security hazard if you have others using your computer and security is a concern, you may like to add a password to your LILO or Grub prompt to stop this from being done. umask The umask umaskis a value valueset setby the root rootuser userof the system.system It controls controlsthe default defaultpermissions of any file filecreated. It has an unusual way of doing things ...to set setthe umask umaskyou must mustdescribedescribe file filepermissions permissionsby saying what will be disabled.disabled You can do this by doing 777 minus minusthe file filepermissions permissionsyou want. Note that umask works workswith numbers numbersonly, for an explanation explanationsee Example:You want the default defaultto be equivalent equivalentto chmod chmod750 (user has r/w/x, group grouphas r/x and other has no permissions), then the command commandyou would use would be:Some basic Security Tools md5sum md5sumCompute an md5 md5checksum (128-bit) for file file“file_name” to verify verifyit's integrity.integrity You normally use the “ md5sum md5sum-c” option optionto check checkagainst a given file file(often with a “.asc” extention) to check checkwhether the various files filesare correct,correct this comes in handy handywhen downloading downloadingisos as the checking checkingis automated automatedfor you. Command Commandsyntax:mkpasswd -l 10 mkpasswdThis command commandwill make a random randompassword passwordof length lengthten characters.characters This password passwordgenerator generatorcreates passwords passwordsthat are designed designedto be hard to guess.guess There are similar similaralternatives alternativesto this program programscattered scatteredaround the internet.internet File PermissionsUse ls ls-l to see the permissions permissionsof files files(list-long). They will appear like this, note that I have added spaces spacesbetween permissionspermissions to make it easier to read:readWhere: r r= read,read w w= write,write x = execute execute - rwx rw- r-- 1 newuser newuser typeownergroupothers This number is the number of hard links (pointers) to this file. You can use ln to create another hard-link to the file. This is the type of file. '-' means a regular file, 'd' would mean a directory, 'l' would mean a link. There are also other types such as 'c' for character device and 'b' for block device (found in the /dev/ directory). These are the permissions for the owner of the file (the user who created the file). These are the permissions for the group, any users who belong is the same group as the user who created the file will have these permissions. These are the permissions for everyone else. Any user who is outside the group will have these permissions to the file. The two names at the end endare the username usernameand group grouprespectively.respectively chmod chmodChange Changefile access accesspermissions for a file(s).There are two methods methodsto change changepermissions using chmod; letters lettersor numbers.numbersLetters Method: use a + or - (plus or minus minussign) to add addor remove removepermissions for a file.file Use an equals equalssign =, to specify specifynew newpermissions and remove removethe old oldones for the particular particulartype of user(s). You can use chmod chmodletter where the letters lettersare:a (all (everyone)), u (user), g (group) and o (other).Examples:This would give the user userread and write writepermission.This will remove removeread/write/execute permissions permissionsfrom other users users(doesn't include includeusers within your group).This will give everyone everyoneread permission permissionfor the file.fileThis would give everyone everyoneexecute and read readpermission permissionto the file,file if anyone had write writepermission it would be removed.Numbers Method: you can also use numbers numbers(instead of letters) to change changefile permissions.permissions Where: r r(read) = 4 w w(write) = 2 x (execute) = 1 Numbers Numberscan be added together togetherso you can specify specifyread/write/execute permissions;permissions read+write = 6, read+execute = 5, read+write+execute = 7Examples:This would give everyone everyoneread/write/execute permission permissionon “this_file”. The first number numberis user,user second is group groupand third is everyone everyoneelse (other).This would give the user userread and execute executepermission,permission and the group groupwritewrite permission permission(but not read readpermission!) and everyone everyoneelse execute executepermission. (Note that it's just an example, settings like that don't really make sense...). chown chownChanges the ownership ownershiprights rightsof a file file(hence the name 'chown' - changechange owner). This program programcan only be used by root.root Use the -R -R option optionto change changethings recursively,recursively in other words,words all matching matchingfilesfiles including includingthose in subdirectories.subdirectories Command Commandsyntax:sticky  bit, sticky stickybit bitOnly the person personwho created the file filemay delete deleteit, even evenif other people peoplehave write writepermission. You can turn turnit on by typing: or (where t represents representsthe sticky stickybit)To turn turnit off offyou would need to type:or (where t represents representsthe sticky stickybit)Note that the permissions permissionsaren't relevant relevantin the numbers numbersexample,example only the first number number(1 = on, 0 = off). Sticky Directories You may also have sticky directories, the /tmp directory is usually an example of a sticky directory. The files inside can only be deleted by the super-user (root) or the creator of the file. Sticky directories will show a 't' at the end of their file permissions (when listed using ls -l). This may be useful when you have a directory that everyone has access to but no-one should be deleting each others files. suid Allow SUID/SGID (switch user userID/switch group groupID) access.access You would normally use chmod to turn turnthis on or off offfor a particular particularfile, suid suidis generally considered a security securityhazard so be careful carefulwhen using this. Example:This will give everyone everyonepermission permissionto execute executethe file filewith the permissionspermissions of the user userwho set setthe +s switch.switch Security Hazard This is obviously a security hazard. You should avoid using the suid flag unless necessary. chattr Change file system attributes (works on ext2fs and possibly others...). Use the -R option optionto change changefiles filesrecursively, chattr chattrhas a large number numberof attributes attributeswhich can be set seton a file,file read readthe manualmanual page pagefor further information.informationExample:This example and tiny parts of the explanation have been taken from the Linux Online Classroom, see [4] in the for further information. This sets setsthe 'immutable' flag flagon a file.file Use a '+' to add addattributes attributesand a '-' to take takethem away. The +i will prevent preventany changes (accidental or otherwise) to the “lilo.conf” file.file If you wish to modify modifythe lilo.liloconf file fileyou will need to unset unsetthe immutableimmutable flag:flag chattr chattr-i. Note some flags flagscan only be used by root;root -i, -a and probably probablymany others.Note there are many different differentattributes attributesthat chattr chattrcan change,change here are a few more morewhich whichmay be useful:A (no Access Accesstime) --- if a file fileor directory directoryhas this attribute attributeset,set whenever it is accessed,accessed either for reading readingof for writing,writing it's last lastaccess timetime will not be updated.updated This can be useful, for example,example on files filesor directories directorieswhich are very often accessed accessedfor reading,reading especially especiallysince this parameter parameteris the only one which whichchanges on an inode inodewhen it's opened openedread-only.a (append only) --- if a file filehas this attribute attributeset setand is open openfor writing,writing the only operation operationpossible will be to append appenddata datato it's previous previouscontents. For a directory,directory this means that you can only add addfiles filesto it, but not rename renameor delete deleteany existing existingfile. Only root rootcan set setor clear this attribute.attributes (secure deletion) --- when such a file fileor directory directorywith this attributeattribute set setis deleted,deleted the blocks blocksit was occupying occupyingon disk diskare written writtenback with zeroes zeroes(similar to using shred). Note that this does work workon the ext2,ext2 and ext3 ext3filesystems filesystemsbut is unlikelyunlikely to work workon others (please see the documentation documentationfor the filesystem filesystemyou are using). Or try tryusing shred shredwhen you want to delete deletethe file filesee lsattr lsattr(list attributes). This will list listif whether a file filehas any special specialattributes (as set setby chattr). Use the -R option optionto list listrecursively recursivelyand try tryusing the -d option optionto list listdirectories directorieslike other files filesrather than listing listingtheir contents.contents Command Commandsyntax:This will list listfiles filesin the current currentdirectory,directory you may also like to specifyspecify a directory directoryor a file:file Archiving FilesThe archiving archivingfiles chapter provides providessome basic basicinformation informationon the simple programs programsthat you can use to archive archivefiles.files You will often see these programs programsused when you try tryto install installprograms without using a package packagemanagement tool.tool This is not a backup guide Please note that while tar is useful for regular purposes, and possibly combined with bash sciprting or similar it can become useful, it is not a great program for performing real backups of data. You should try searching the internet if you are looking for backup programs on GNU/Linux or try Sourceforge or Freshmeat for programs that you can use. You may also like to see rsync, . tar (tape archiver)Type tar then -option(s)Options Optionslist:listcdefault --- create.vdefault --- verbose,verbose give more moreoutput,output show showwhat files filesare being worked with (extracted or added).f default--- file file(create or extract extractfrom file) - should always be the last lastoption otherwise the command commandwill not work.work zdefault --- put the file filethough gzip gzipor use gunzip gunzipon the file filefirst.xdefault --- extract extractthe files filesfrom the tarball.tarballpdefault --- preserves preservesdates,dates permissions permissionsof the original originalfiles.filesjdefault --- send sendarchive through bzip2.bzip2--exclude=pattern --- this will stop stopcertain files filesfrom being archived archived(using a standard standardwild wildcard pattern) or a single file filename.tar examples  This would create a tape tapearchive (no compressing).This would extract extractfiles files(verbosely) from a gzipped gzippedtape tapearchive. rsync rsync rsyncrsync is a replacement replacementfor the old oldrcp (remote-copy) command.command It can use ssh for encryption encryptionand is a very flexible flexibletool,tool it can copy copyfrom local localmachinemachine to local localmachine,machine from local localto remote remote(and vice-versa), and to and from rsync rsyncservers.servers rsync uses an advanced advanceddifferencing algorithm,algorithm so when to copies copiesor syncs syncssomething it will (a) only copy copynew/changed files filesand (b) if the files fileshave being changed it will copy copythe differences differencesbetween the files files(not the entireentire file). Using this method methodrsync saves savestime timeand bandwidth.bandwidth rsync also has advanced advancedexclusion options optionssimilar to GNU GNUtar.tar rsync has a well written writtenmanual page,page for further information informationread the rsync documentation documentationonline or type:If you wish to visit visitthe rsync rsyncsite you will find findit over here CompressionThere are two main compression compressionutilities utilitiesused in GNU/Linux. It's normal normalto first “tar” a bunch bunchof files files(using the tar program programof course) and then compress compressthem with either bzip2 or gzip. Of course either of these tools toolscould be used without tar,tar although they are not designed designedto work workon more morethan one file file(they use the UNIX UNIXtools philosophy,philosophy let lettar group the files, they will do the compression...this simplifies their program). It's normal normalto use tar and then use these tools toolson them, or use tar with the correct correctoptions to use these compression compressionprograms.programsGNU zip (gzip) gzip gzipis the GNU GNUzip zipcompression program programand probably probablythe most common commoncompression format formaton UNIX-like UNIX-likeoperating systems.systemsThis will compress compressa tar tararchive archivewith GNU GNUzip,zip usually with a .gz .gzextension. Gzip Gzipcan compress compressany type of file,file it doesn't have to be a tar tararchive.archiveThis will decompress decompressa gzipped gzippedfile, and leave the contents contentsin the currentcurrent directory.directorybzip2 bzip2 bzip2is a newer newercompression program programwhich whichoffers superior superiorcompression to gzip gzipat the cost costof more moreprocessor processortime.timeThis will compress compressa tar tararchive archivewith the bzip2 bzip2compression program,program usually with a .bz .bzextension. bzip2 bzip2can compress compressany type of file,file it doesn't have to be a tar tararchive.archive This will decompress decompressa file filecompressed compressedby bzip2,bzip2 and leave the contentscontents in the current currentdirectory.directory zipinfo zipinfoUse zipinfo to find finddetailed detailedinformation informationabout a zip ziparchive (the ones usually generally used by ms-dos ms-dosand windows,windows for example examplewinzip). Command Commandsyntax: zipgrep zipgrepWill run rungrep to look lookfor files fileswithin a zip zipfile (ms-dos style,style for example examplewinzip) without manually manuallydecompressing the file filefirst. Command Commandsyntax: bzip2recover bzip2recoverUsed to recover recoverfiles filesfrom a damaged damagedbzip2 archive.archive It simply extracts out all the working workingblocks blocksas there own bzip2 bzip2archives,archives you can than use bzip2 bzip2-t -ton each file fileto test testthe integrity integrityof them and extract extractthe working workingfiles. bzme bzmeWill convert converta file filethat is zipped zippedor gzipped gzippedto a file filecompressedcompressed using bzip2. Command Commandsyntax: Tip Both gzip and bzip2 supply tools to work within compressed files for example listing the files within the archive, running less on them, using grep to find files within the archive et cetera. For gzip the commands are prefixed with z, zcat, zless, zgrep. For bzip2 the commands are prefixed with bz, bzcat, bzless, bzgrep. Graphics tools (command line based)The graphics graphicstools chapter explains explainssome image imageprograms programsthat can be called from the command-line.command-line While I have found foundimage imageprograms programsthat can be used from the command-line,command-line zgv zgvis the only one I've ever heard of, I did not find findthem very useful. All the tools toolslisted listeduse the X windowing windowingsystem systemto work workand simply runrun from the command commandline (so they can be scripted/automated if necessary). montage montageCreates a 'montage', an image imagecreated of many other images,images arrangedarranged in a random randomfashion. Command Commandsyntax:The above would create a “montage” of images images(it would tile tilea certain number numberof images) into a composite compositeimage called “skyline_images.miff”, you could always use display displayto view viewthe image.image Note Note that the images are converted to the same size (scaled) so they can be tiled together. convert To convert convertthe file fileformat formatof an image imageto another image imageformat. convert is used to change changea files filesformat,format for example examplefrom a jpeg jpegto a bitmap bitmapor one of many other formats.formats convert convertcan also manipulate manipulatethe images imagesas well (see the man manpage pageor the ImageMagickImageMagick site). Example Examplefrom Jpeg Jpegto PNG PNGformat: import importCaptures screen-shots screen-shotsfrom the X server serverand saves savesthem to a file.file A screen-dump screen-dumpof what X is doing. Command Commandsyntax: display displaydisplay is used to display display(output) images imageson the screen.screen Once open openyou are can also perform performediting editingfunctions and are able ableto read/write images.images It has various interesting options optionssuch as the ability abilityto display displayimagesimages as a slide slideshow showand the ability abilityto capture capturescreenshots of a single windowwindow on-screen.on-screen Command Commandsyntax (for displaying an image):To display displaya slide slideshow showof images, open openthe images imagesyou want possibly possiblyusing a wild wildcard, for example:exampleAnd then click clickon the image imageto bring up the menu menuand then look lookunder the miscellaneous miscellaneousmenu menufor the slide slideshow showoption. Speed Warning Be careful when opening multiple large sized images (especially on a slow machine) and putting the slide show on a small delay between image changes. Your processor will be overloaded and it will take a significant amount of time to be able to close ImageMagick. identify Will identify identifythe type of image imageas well as it's size,size colour colourdepth and various other information.information Use the -verbose -verbose option optionto show showdetailed detailedinformation informationon the particular particularfile(s). Command Commandsyntax: mogrify mogrifymogrify is another ImageMagick ImageMagickcommand commandwhich is used to transform transformimages imagesin a numbernumber of different differentways, including includingscaling,scaling rotation rotationand various other effects.effects This command commandcan work workon a single file fileor in batch.batchFor example,example to convert converta large number numberof tiff tifffiles filesto jpeg jpegfiles you could type:This command commandhas the power powerto do a number numberof things in batch batchincluding making thumbnails thumbnailsof sets setsof images.imagesFor this you could type:This example has come been used from (unedited) “CLI for noobies: import, display, mogrify”, see [16] in the for further information. showrgb showrgbshowrgb is used to uncompile uncompilean rgb rgbcolour-name database.database The default defaultis the one that X was built builtwith. This database databasecan be used to find findthe correct correctcolour colourcombination for a particular particularcolour colour(well it can be used as a rough roughguide guideanyway). To list listthe colours coloursfrom the X database,database simply type: Please note: All tools listed, excluding showrgb are part of the ImageMagick package. Type man ImageMagick for a full list of available commands. Or see the ImageMagick site ImageMagick for further information. Working with MS-DOS filesUse the mtools mtoolsprograms programsto work workwith MS-DOS MS-DOSbased files,files execute executemtools for a full fulllisting listingof available availablem* tools.tools There are a lot of files fileswithin the mtools mtoolspackage packagefor working workingwith MS-DOSMS-DOS disks,disks also try trythe info infodocumentation documentationof mtools mtoolsfor more moredetails.details The use of slashes Note that with mtools commands you can use the slashes on the a: part either way (ie. backslash (windows-style) or forward slash (UNIX system style)). mformat mformatFormats Formatsan unmounted unmounteddisk as an ms-dos ms-dosfloppy disk.disk Usage Usageis similar similarto the ms-dos ms-dosformat formatutility,utility to format formatthe first floppyfloppy disk diskyou can type: mcopy mcopyCopies files filesfrom an ms-dos ms-dosdisk diskwhen it's not mounted.mounted Similar to the ms-dos ms-doscopy copycommand except it's more moreadvanced.advanced Command Commandsyntax: mmount mmountMount an ms-dos ms-dosdisk,disk without using the normal normalUNIX system systemmount.For example:exampleThis will mount mountthe floppy floppyunder /mnt/floppy (this option optionmay or may not be necessary, it depends on your /etc/fstab setup). mbadblocks mbadblocksScans Scansan ms-dos ms-dos(fat formatted formatteddisk) for bad blocks,blocks it marksmarks any unused unusedbad blocks blocksas “bad” so they won't be used. Example: dosfsck dosfsckThis program programis used to check checkand repair repairms-dos based filesystems.filesystems Use the -a option optionto automatically automaticallyrepair repairthe filesystem filesystem(ie don't ask the user userquestions), the -t option optionto mark markun-readable un-readableclusters clustersas bad and the -v option optionto be more moreverbose verbose(print more moreinformation).Example:This would check checkyour floppy floppydisk diskfor any errors errors(and bad sectors) and repairrepair them automatically.automatically Scheduling Commands to run in the backgroundThere are two main tools toolsused to perform performscheduled scheduledtasks, at and cron. You may also like to try tryanacron if your computer computerdoes not run runcontinuously, as cron cronwill only work workif your computer computeris left lefton (anacron can catch catchup with the scheduled scheduledtasks the next time the computer is on...).at at'at' executes a command commandonce on a particular particularday,day at a particular particulartime.time at will add adda particular particularcommand commandto be executed.Examples:You then type the commands commandsyou want executed then press pressthe end-of-fileend-of-file character character(normally CTRL D CTRL-D ). Also try:tryThis will run runat at the current currenttime time+ the hours/mins/seconds you specifyspecify (use at now + 1 hour hourto have command(s) run in 1 hour from now...)You can also use the -f option optionto have at execute executea particular particularfile (a shell shellscript).This would run runthe shell shellscript 1 hour hourfrom now. atq atqWill list listjobs currently in queue queuefor the user userwho executed it, if rootroot executes at it will list listall jobs jobsin queue queuefor the at daemon.daemon Doesn't need or take takeany options.options atrm atrmWill remove removea job jobfrom the 'at' queue.queue Command Commandsyntax:Will delete deletethe job job“job_no” (use atq to find findout the number numberof the job)cron croncron can be used to schedule schedulea particular particularfunction functionto occur occurevery minute,minute hour,hour day,day week,week or month.month It's normal normalto use the crontab crontabto perform performthe editing editingfunctions as this automates automatesthe process processfor the cron crondaemon daemonand makes it easier for normalnormal users usersto use cron.cron Anacron anacron is another tool designed for systems which are not always on, such as home computers While cron will not run if the computer is off, anacron will simply run the command when the computer is next on (it catches up with things). crontab crontabcrontab is used to edit,edit read readand remove removethe files fileswhich the cron crondaemon daemonreads.reads Options Optionsfor crontab crontab(use crontab crontab-option(s)):-e --- to edit editthe file.file-l --- to list listthe contents contentsof the file.file -u -uusername --- use the -u with a username usernameargument argumentto work workwith another users userscrontab crontabfile.When using crontab crontab-e -eyou have a number numberof fields fields(6) what they mean meanis listed listedbelow: Field Allowed Values minute 0-59 hour 0-23 day of month 1-31 month 1-12 (or names, see below) day of week 0-7 (0 or 7 is Sun, or use three letter names) There are also a number numberof shortcut shortcutmethods for common commontasks, including:includingThis information has come from (without editing) a post on the LinuxChix techtalk mailing list, please see [16] in the for further information.@reboot --- run runcommand commandat reboot reboot@yearly --- same as 0 0 1 1 * @annually --- same as @yearly @monthly --- same as 0 0 1 * * @weekly --- same as 0 0 * * 0 @daily --- same as 0 0 * * * @midnight --- same as @daily @hourly --- same as 0 * * * * This information comes from the cron manual page with small additions (no changes to original content), refer to [13] in the for further information.Note that * (asterisk) is used to mean meananything (similar to the wildcard). For example exampleif you leave the day daypart (the 5th place) with an asteriskasterisk it would mean meaneveryday.everyday Lists Listsare allowed.allowed A list listis a set setof numbers numbers(or ranges) separated separatedby commas.commas Examples:Examples ``1,2,5,9'', ``0-4,8-12”. Step Stepvalues valuescan be used in conjunction conjunctionwith ranges.ranges Following Followinga range rangewith ``/<number>'' specifies specifiesskips of the number's valuevalue through the range.range For example,example ``0-23/2'' can be used in the hours hoursfield fieldto specify specifycommandcommand execution executionevery other hour hour(the alternative alternativein the V7 V7standard is ``0,2,4,6,8,10,12,14,16,18,20,22''). Steps Stepsare also permitted permittedafter an asterisk,asterisk so if you want to say ``every two hours'', just use ``*/2''.When writing writinga crontab crontabentry entryyou simply type in six sixfields separated separatedby spaces,spaces the first five fiveare those listed listedin the table table(using numbers numbersor letters lettersand numbers numbersas appropriate), the 6th field fieldis the command commandto be executed and any options,options cron cronwill read readeverything everythingup until untilthe newline.newlineExample:This would run runthe echo echocommand with the string stringshown at 4:05 every Sunday.Sunday MiscellaneousThe miscellaneous miscellaneouschapter contains commands commandsthat don't really reallyfit into the other sections sectionsof this guide.guiderenaming  extensions extensionsTo rename renameall of the files filesin the current currentdirectory directorywith a '.htm' extension extensionto '.html', type:You can get a copy copyof the chcase chcase perl perlscript here.For more morecomplex complexrenaming renamingyou should read readrelThis information information comes from the Linux Cookbook (without editing). See [3] in the for further information. Use rel relto analyze analyzetext files filesfor relevance relevanceto a given set setof keywords.keywords It outputs outputsthe names of those files filesthat are relevant relevantto the given keywords,keywords ranked rankedin order orderof relevance;relevance if a file filedoes not meet meetthe criteria,criteria it is not outputted in the relevance relevancelisting.units man  page pageThere is a man manpage, part partof the Linux LinuxProgrammers ProgrammersManual called “units”. It displays various information informationon the various scientific scientificmeasurementsmeasurements (such as mega,mega giga gigaet cetera). This manual manualpage pagealso has a short shortdiscussion about the argument argumentover whichwhich standard standardshould be used to measure measuredata (ie. the kibibyte kibibytevs kilobyte). To access accessthis man manpage pagetype:fortune fortunefortune is a tool toolwhich will print printa random,random hopefully interesting quote quoteor entertaining short shortpiece pieceof writing.writing There are options optionsto customise customisewhich area areathe epigrams epigramsshould come from. Just type fortune to get a random randomepigram epigramfrom any section.section Simply type: Mini-GuidesThe mini-guides mini-guideschapter is a section sectionof the document documentthat describes describescertain concepts conceptsin more moredepth depththan the usual command commanddescriptions.descriptions The information informationlisted is fairly specific specificas I have tried triedto avoid avoidthe duplication duplicationof too much information informationthat is already online.onlineRPM: Redhat Package Management System Checking Checking Installed InstalledRPM'sUse the rpm rpm-V-V option optionto check check