{
"pages": [
{
"page_number": 1,
"text": ""
},
{
"page_number": 2,
"text": "Linux 101 Hacks www.thegeekstuff.com\nTable of Contents\nIntroduction\n \n \n \n \n...........................................................\n \n 7 \nAbout the Author\n \n \n \n \n....................................................\n \n 8 \nCopyright & Disclaimer\n \n \n \n \n............................................\n \n 9 \nVersion\n \n \n \n \n..............................................................................\n \n 9 \nMore eBooks from The Geek Stuff\n \n \n \n \n..........................\n \n 10\n \nBash 101 Hacks\n \n \n \n \n...............................................................\n \n 10\n \nSed and Awk 101 Hacks\n \n \n \n \n...................................................\n \n 11\n \nNagios Core\n \n \n \n \n.....................................................................\n \n 12\n \nVim 101 Hacks\n \n \n \n \n.................................................................\n \n 13\n \nChapter 1: Powerful CD Command Hacks\n \n \n \n \n................\n \n 14\n \nHack 1. Define CD Base Directory Using CDPATH \n \n \n \n \n...............\n \n 14\n \nHack 2. Use CD Alias to Navigate Up the Directory\n \n \n \n \n.............\n \n 15\n \nHack 3. Perform mkdir and cd Using a Single Command \n \n \n \n \n....\n \n 18\n \nHack 4. Toggle Between Directories \n \n \n \n \n.................................\n \n 19\n \nHack 5. Manipulate Directory Stack\n \n \n \n \n..................................\n \n 20\n \nHack 6. Automatically Correct Mistyped Directory Names \n \n . 23\n \nChapter 2: Essential Linux Commands \n \n \n \n \n...................\n \n 24\n \nHack 7. Grep Command \n \n \n \n \n...................................................\n \n 24\n \nHack 8. Regular Expression in Grep\n \n \n \n \n..................................\n \n 26\n \nHack 9. Find Command \n \n \n \n \n....................................................\n \n 29\n \nHack 10. Suppress Standard Output and Error Message \n \n \n \n \n....\n \n 31\n \nHack 11. Join Command \n \n \n \n \n...................................................\n \n 32\n \nHack 12. Change the Case \n \n \n \n \n...............................................\n \n 33\n \nHack 13. Xargs Command \n \n \n \n \n................................................\n \n 34\n \nHack 14. Sort Command \n \n \n \n \n..................................................\n \n 35\n \nHack 15. Uniq Command \n \n \n \n \n..................................................\n \n 37\n \nHack 16. Cut Command \n \n \n \n \n...................................................\n \n 38\n \nHack 17. Stat Command \n \n \n \n \n..................................................\n \n 39\n \nHack 18. Diff Command \n \n \n \n \n...................................................\n \n 41\n \n2\n"
},
{
"page_number": 3,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 19. Display Total Connect Time of Users \n \n \n \n \n...................\n \n 42\n \nHack 20. Execute Commands in the Background \n \n \n \n \n...............\n \n 43\n \nHack 21. Sed Basics - Find and Replace Using RegEx \n \n \n \n \n........\n \n 45\n \nHack 22: Awk Introduction – Print Examples \n \n \n \n \n.....................\n \n 50\n \nHack 23. Vim Editor Navigation Fundamentals \n \n \n \n \n..................\n \n 56\n \nHack 24. Chmod Command Examples\n \n \n \n \n................................\n \n 60\n \nHack 25. View Multiple Log Files in One Terminal \n \n \n \n \n..............\n \n 62\n \nHack 26. Less Command\n \n \n \n \n...................................................\n \n 64\n \nHack 27. Wget Examples \n \n \n \n \n.................................................\n \n 68\n \nChapter 3: SSH Commands and Tips\n \n \n \n \n.......................\n \n 76\n \nHack 28. Debug SSH Client Session \n \n \n \n \n..................................\n \n 76\n \nHack 29. Toggle SSH Session using SSH Escape Character \n \n . 77\n \nHack 30. Display SSH Session Statistics \n \n \n \n \n...........................\n \n 78\n \nHack 31. Change OpenSSH Security Options\n \n \n \n \n......................\n \n 79\n \nHack 32. Transfer All PuTTY Sessions\n \n \n \n \n................................\n \n 85\n \nChapter 4: Date Manipulation \n \n \n \n \n...............................\n \n 87\n \nHack 33. Set System Date and Time \n \n \n \n \n.................................\n \n 87\n \nHack 34. Set Hardware Date and Time \n \n \n \n \n.............................\n \n 88\n \nHack 35. Display Date and Time in a Specific Format \n \n \n \n \n........\n \n 89\n \nHack 36. Display Past Date and Time \n \n \n \n \n...............................\n \n 90\n \nHack 37. Display Future Date and Time \n \n \n \n \n............................\n \n 91\n \nChapter 5: PS1, PS2, PS3, PS4 and \nPROMPT_COMMAND\n \n \n \n \n..............................................\n \n 93\n \nHack 38. PS1 - Default Interaction Prompt \n \n \n \n \n.......................\n \n 93\n \nHack 39. PS2 - Continuation Interactive Prompt \n \n \n \n \n...............\n \n 94\n \nHack 40. PS3 - Prompt Used by Select Command\n \n \n \n \n...............\n \n 95\n \nHack 41. PS4 - Prompt to Prefix Tracing Output \n \n \n \n \n................\n \n 97\n \nHack 42. PROMPT_COMMAND \n \n \n \n \n..........................................\n \n 98\n \nHack 43. Customize Bash Prompt Using PS1\n \n \n \n \n......................\n \n 99\n \nHack 44. Colorful Bash Prompt Using PS1\n \n \n \n \n........................\n \n 104\n \n \nChapter 6: Archive and Compression\n \n \n \n \n....................\n \n 109\n \n \nHack 45. Zip Command Basics \n \n \n \n \n........................................\n \n 109\n \n \nHack 46. Zip Command Advanced Compression\n \n \n \n \n...............\n \n 111\n \n \n3\n"
},
{
"page_number": 4,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 47. Password Protection of Zip files \n \n \n \n \n.......................\n \n 113\n \n \nHack 48. Tar Command Examples \n \n \n \n \n...................................\n \n 113\n \n \nHack 49. Combine gzip, bzip2 with Tar \n \n \n \n \n...........................\n \n 115\n \n \nHack 50. BZ is Eazy! Bz* Command Examples\n \n \n \n \n..................\n \n 116\n \n \nHack 51. Cpio Examples \n \n \n \n \n.................................................\n \n 120\n \n \nChapter 7: Command Line History \n \n \n \n \n.......................\n \n 124\n \n \nHack 52. Bash Command Line History Examples\n \n \n \n \n..............\n \n 124\n \n \nHack 53. History Related Environment Variables\n \n \n \n \n..............\n \n 128\n \n \nHack 54. History Expansion Examples \n \n \n \n \n............................\n \n 133\n \n \nChapter 8: System Administration Tasks\n \n \n \n \n...............\n \n 136\n \n \nHack 55. Partition Using fdisk\n \n \n \n \n.........................................\n \n 136\n \n \nHack 56. Format a Partition Using mke2fsk \n \n \n \n \n....................\n \n 138\n \n \nHack 57. Mount a Partition \n \n \n \n \n............................................\n \n 140\n \n \nHack 58. Fine Tune a Partition Using tune2fs \n \n \n \n \n..................\n \n 140\n \n \nHack 59. Create a Swap File System\n \n \n \n \n................................\n \n 142\n \n \nHack 60. Create a New User\n \n \n \n \n............................................\n \n 143\n \n \nHack 61. Create a New Group \n \n \n \n \n........................................\n \n 145\n \n \nHack 62. Setup SSH Passwordless Login in OpenSSH \n \n \n \n \n.......\n \n 146\n \n \nHack 63. Use ssh-copy-id Along With ssh-agent \n \n \n \n \n..............\n \n 147\n \n \nHack 64. Crontab Examples\n \n \n \n \n............................................\n \n 149\n \n \nHack 65. Safe Reboot Of Linux Using Magic SysRq Key \n \n \n \n \n....\n \n 151\n \n \nHack 66. Linux Parted Command Examples \n \n \n \n \n.....................\n \n 153\n \n \nHack 67. Rsync Command Examples \n \n \n \n \n...............................\n \n 164\n \n \nHack 68. Chkconfig Command Examples\n \n \n \n \n..........................\n \n 169\n \n \nHack 69. How to Setup Anacron\n \n \n \n \n......................................\n \n 174\n \n \nHack 70. IPTables Rules Examples \n \n \n \n \n..................................\n \n 178\n \n \nChapter 9: Install Packages\n \n \n \n \n..................................\n \n 181\n \n \nHack 71. Yum Command Examples\n \n \n \n \n..................................\n \n 181\n \n \nHack 72. RPM Command Examples\n \n \n \n \n..................................\n \n 184\n \n \nHack 73. apt-* Command Examples\n \n \n \n \n.................................\n \n 188\n \n \nHack 74. Install from Source\n \n \n \n \n...........................................\n \n 190\n \n \nChapter 10: LAMP Stack\n \n \n \n \n......................................\n \n 192\n \n \nHack 75. Install Apache 2 with SSL\n \n \n \n \n..................................\n \n 192\n \n \n4\n"
},
{
"page_number": 5,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 76. Install PHP from Source \n \n \n \n \n...................................\n \n 196\n \n \nHack 77. Install MySQL \n \n \n \n \n..................................................\n \n 199\n \n \nHack 78. Install LAMP Stack\n \n \n \n \n............................................\n \n 204\n \n \nHack 79. Install XAMPP\n \n \n \n \n..................................................\n \n 210\n \n \nHack 80. Secure Your Apache Web Server \n \n \n \n \n.......................\n \n 212\n \n \nHack 81. Apachectl and Httpd Tips\n \n \n \n \n..................................\n \n 216\n \n \nHack 82. Setup Apache Virtual Host Configuration\n \n \n \n \n...........\n \n 223\n \n \nHack 83. Rotate Apache Logs Files\n \n \n \n \n..................................\n \n 225\n \n \nChapter 11: Bash Scripting\n \n \n \n \n..................................\n \n 228\n \n \nHack 84. Execution Sequence of .bash_* files\n \n \n \n \n..................\n \n 228\n \n \nHack 85. Bash FOR Loops Using C Like Syntax \n \n \n \n \n................\n \n 232\n \n \nHack 86. Debug a Shell Script\n \n \n \n \n.........................................\n \n 234\n \n \nHack 87. Quoting\n \n \n \n \n...........................................................\n \n 236\n \n \nHack 88. Read Data File Fields Inside a Shell Script \n \n \n \n \n........\n \n 237\n \n \nChapter 12: System Monitoring and Performance\n \n \n \n..\n 239\n \n \nHack 89. Free Command\n \n \n \n \n.................................................\n \n 239\n \n \nHack 90. Top Command \n \n \n \n \n.................................................\n \n 240\n \n \nHack 91. Df Command \n \n \n \n \n...................................................\n \n 243\n \n \nHack 92. Du Command \n \n \n \n \n...................................................\n \n 244\n \n \nHack 93. Lsof Commands \n \n \n \n \n...............................................\n \n 245\n \n \nHack 94. Vmstat Command \n \n \n \n \n............................................\n \n 247\n \n \nHack 95. Netstat Command \n \n \n \n \n...........................................\n \n 248\n \n \nHack 96. Sysctl Command \n \n \n \n \n..............................................\n \n 251\n \n \nHack 97. Nice Command \n \n \n \n \n................................................\n \n 252\n \n \nHack 98. Renice Command \n \n \n \n \n.............................................\n \n 254\n \n \nHack 99. Kill Command \n \n \n \n \n..................................................\n \n 256\n \n \nHack 100. Ps Command\n \n \n \n \n..................................................\n \n 258\n \n \nHack 101. Sar Command \n \n \n \n \n................................................\n \n 260\n \n \nYour Support is Appreciated \n \n \n \n \n................................\n \n 264\n \n \nBash 101 Hacks \n \n \n \n \n.............................................................\n \n 264\n \n \nSed and Awk 101 Hacks \n \n \n \n \n.................................................\n \n 264\n \n \nNagios Core 3 \n \n \n \n \n...............................................................\n \n 265\n \n \nVim 101 Hacks \n \n \n \n \n..............................................................\n \n 265\n \n \n5\n"
},
{
"page_number": 6,
"text": "Linux 101 Hacks www.thegeekstuff.com\n10 Amazing and Essential Linux Books \n \n \n \n \n.................\n \n 266\n \n \nExtended Reading\n \n \n \n \n...............................................\n \n 269\n \n \nMore Linux Articles\n \n \n \n \n........................................................\n \n 270\n \n \nThank You\n \n \n \n \n...........................................................\n \n 271\n \n \n6\n"
},
{
"page_number": 7,
"text": "Linux 101 Hacks www.thegeekstuff.com\nIntroduction\nThere are total of 101 hacks in this book that will help you build a strong \nfoundation in Linux. All the hacks in this book are explained with \nappropriate Linux command examples that are easy to follow.\nThis book contains 12 chapters. \n•\nChapters 1 – 3 explain OpenSSH tips and tricks, CD command \nhacks, and several essential Linux commands including grep, find \nand many more.\n•\nChapters 4 – 6 cover date manipulation, Linux command prompt \ncustomization, archive and compression commands. Clear \nexamples are provided.\n•\nChapter 7 – 9 explain critical Linux sysadmin tasks, package \ninstallation on various distros, and bash command line history \nwith clear examples\n•\nChapter 10 - 12 cover LAMP stack installation and several Linux \nsystem monitoring and performance commands with practical \nexamples.\nA note on the examples: Most examples are identified in the following \nway.\nExample Description\nLines of code for you to type, with the result you will \nsee on screen.\nAdditional clarification or discussion will appear below the code section \nin plain text.\n7\n”There are only 10 types of people in the world — those who \nunderstand binary, those who don’t, and those who understand \ngray code”\n— Geek\n"
},
{
"page_number": 8,
"text": "Linux 101 Hacks www.thegeekstuff.com\nAbout the Author\nI’m Ramesh Natarajan, author of The Geek \nStuff blog thegeekstuff.com and numerous \nebooks including this one.\nI have done extensive programming in \nseveral languages and C is my favorite. I \nhave done a lot of work on the \ninfrastructure side including Linux system \nadministration, DBA, Networking, \nHardware and Storage (EMC).\nI also developed passworddragon.com — a free, easy and secure \npassword manager that runs on Windows, Linux and Mac.\nApart from this Linux 101 Hacks eBook, I've also published the following \nebooks:\n•\nVim 101 Hacks\n \n \n•\nNagios Core 3\n \n \n•\nSed and Awk 101 Hacks\n \n \n•\nBash 101 Hacks\n \n \nIf you have any questions while reading this book, don't hesitate to \nreach out to me. You can connect with me on the following:\n•\nTwitter (@t\n hegeekstuff\n \n )\n•\nFacebook page\n \n \nIf you want to write to me directly, use this contact form to reach out to \nme.\n8\n"
},
{
"page_number": 9,
"text": "Linux 101 Hacks www.thegeekstuff.com\nCopyright & Disclaimer\nCopyright © 2009 - 2011 – Ramesh Natarajan. All rights reserved. No \npart of this book may be reproduced, translated, posted or shared in any \nform, by any means.\nThe information provided in this book is provided \"as is\" with no implied \nwarranties or guarantees.\nVersion\nVersion\nDate\nRevisions\n1.0\n12 – Feb – 2009\nFirst Edition\n2.0\n16 – Nov - 2011\nSecond Edition\n9\n"
},
{
"page_number": 10,
"text": "Linux 101 Hacks www.thegeekstuff.com\nMore eBooks from The Geek Stuff\nBash 101 Hacks\nWhen you are working on a Linux \nenvironment, does any of the following \nsound familiar to you?\n•\nYou are spending significant amount \nof time doing tasks manually, without \nknowing how to automate those \ntasks effectively using scripts.\n•\nYou are executing set of commands \nto complete a task, and retyping the \nsame commands manually with \ndifferent values to complete similar \ntasks.\n•\nYou are having a good understanding \nof all Linux commands, but struggling \nto put them together in a shell script to accomplish a task.\nBash is the default shell on Linux. If you are spending lot of time on \nLinux environment, you should master the Bash command line features \nto become efficient.\nApart from being an interactive shell, Bash is also a scripting language, \nwhich allows you to automate your tasks using Bash shell scripting.\nBash 101 Hacks is a downloadable eBook that contains 101 practical \nexamples on both Bash command line and shell scripting, that will help \nyou understand everything you need to know about Bash.\nGet Your Copy of: Bash 101 Hacks eBook\nhttp://www.thegeekstuff.com/bash-101-hacks-ebook/\n10\n"
},
{
"page_number": 11,
"text": "Linux 101 Hacks www.thegeekstuff.com\nSed and Awk 101 Hacks\nIf you are spending lot of time on UNIX / \nLinux, the following might sound familiar to \nyou.\n•\nYou are manually making the same \nedits on multiple files. Sometimes the \nsame edits are manually repeated on \nfiles on different servers.\n•\nYou are constantly viewing large log \nfiles (or data files), manually looking \nfor certain lines that contain certain \npatterns. Once you find those lines, \nyou are manually copying and pasting \na few relevant fields from those lines \nfor reporting purposes.\n•\nYou are constantly dealing with text files, and spending a lot of \ntime manually manipulating the text files.\nIf you are spending lot of time on UNIX / Linux, you’ll be manipulating \ntext files frequently. You may be making the similar edits on multiple \nconfiguration files on one or more servers. You may be digging huge log \nfiles (or data files) looking for certain information.\nSed and Awk 101 Hacks is a downloadable eBook that contains 101 \npractical examples on various advanced Sed and Awk features, that will \nhelp you understand everything you need to know about Sed and Awk.\nGet Your Copy of: Sed and Awk 101 Hacks eBook\nhttp://www.thegeekstuff.com/sed-awk-101-hacks-ebook/\n11\n"
},
{
"page_number": 12,
"text": "Linux 101 Hacks www.thegeekstuff.com\nNagios Core\nIf you are a sysadmin, dba, network \nadministrator, or someone who is responsible \nfor keeping the IT infrastructure up and \nrunning, the following might sound familiar to \nyou.\n•\nYou don’t know when you’ll run out of \ndisk space, or when the server will go \ndown, or when the database will \ncrash, or when one of the critical \nservices running on the server will \nfail.\n•\nYou are worried that right people (or \nteam) are not getting notified about \nthe server or services issues at the \nright time.\n•\nYou (or your team) are constantly working on finding and fixing \nissues as they show up.\nYou should implement a robust monitoring solution that will notify you \nwhen there is an issue. It should also notify the right people at the right \ntime about a potential issue, even before it becomes critical.\nNagios Core 3 eBook is the only guide you’ll ever need to get your IT \ninfrastructure monitored using Nagios Core, and it will help you to \nunderstand everything you need to know to implement Nagios Core 3.\nGet Your Copy of: Nagios Core eBook\nhttp://www.thegeekstuff.com/nagios-core-ebook/\n12\n"
},
{
"page_number": 13,
"text": "Linux 101 Hacks www.thegeekstuff.com\nVim 101 Hacks\nIf you are spending lot of time on UNIX / \nLinux environment, it is essential to become \ncomfortable with the Vim editor.\nIf you are putting off mastering the Vim \neditor for a later day because learning Vim \neditor is not intuitive, friendly, or fun — you \nare not alone.\nVim editor is very powerful editor that will \nmake you extremely productive once you \ntake some time to learn and understand its \nfeatures. If you are like most people, you \nwould like to have a structured way of \nlearning this powerful editor and take advantage of all its features.\nVim 101 Hacks is a downloadable eBook that contains 101 practical \nexamples on various advanced Vim features that will make you fast and \nproductive in the Vim editor.\nEach hack provided in this eBook is very crisp and easy to understand. \nThe practical examples will show you exactly how to use a particular Vim \nfeature.\nGet Your Copy of: Vim 101 Hacks eBook\nhttp://www.thegeekstuff.com/vim-101-hacks-ebook/\n13\n"
},
{
"page_number": 14,
"text": "Linux 101 Hacks www.thegeekstuff.com\nChapter 1: Powerful CD Command \nHacks\ncd is one of the most frequently used commands during a UNIX session. \nThe 6 cd command hacks mentioned in this chapter will boost your \nproductivity instantly and make it easier to navigate the directory \nstructure from command line. \nHack 1. Define CD Base Directory Using \nCDPATH \nIf you are frequently performing cd to subdirectories of a specific parent \ndirectory, you can set the CDPATH to the parent directory and perform \ncd to the subdirectories without giving the parent directory path as \nexplained below. \n# pwd \n/home/ramesh \n# cd mail \n-bash: cd: mail: No such file or directory \n[Note: The above cd is looking for mail directory under \ncurrent directory] \n# export CDPATH=/etc \n# cd mail \n/etc/mail \n[Note: The above cd is looking for mail under /etc and not \nunder current directory] \n# pwd \n/etc/mail \n \n14\n"
},
{
"page_number": 15,
"text": "Linux 101 Hacks www.thegeekstuff.com\nTo make this change permanent, add export CDPATH=/etc to your \n~/.bash_profile \nSimilar to the PATH variable, you can add more than one directory entry \nin the CDPATH variable, separating them with : , as shown below. \nexport CDPATH=.:~:/etc:/var \nThis hack can be very helpful under the following situations: \n•\nOracle DBAs frequently working under $ORACLE_HOME, can set \nthe CDPATH variable to the oracle home \n•\nUnix sysadmins frequently working under /etc, can set the \nCDPATH variable to /etc \n•\nDevelopers frequently working under project directory \n/home/projects, can set the CDPATH variable to /home/projects \n•\nEnd-users frequently accessing the subdirectories under their \nhome directory, can set the CDPATH variable to ~ (home \ndirectory) \nHack 2. Use CD Alias to Navigate Up the \nDirectory\nWhen you are navigating up a very long directory structure, you may be \nusing cd ..\\..\\ with multiple ..\\’s depending on how many directories you \nwant to go up as shown below. \n# mkdir -p \n/tmp/very/long/directory/structure/that/is/too/deep \n# cd /tmp/very/long/directory/structure/that/is/too/deep \n# pwd \n/tmp/very/long/directory/structure/that/is/too/deep \n# cd ../../../../ \n15\n"
},
{
"page_number": 16,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# pwd \n/tmp/very/long/directory/structure \nInstead of executing cd ../../../.. to navigate four levels up, use one of the \nfollowing four alias methods: \nMethod 1: Navigate up the directory using “..n” \nIn the example below, ..4 is used to go up 4 directory level, ..3 to go up \n3 directory level, ..2 to go up 2 directory level. Add the following alias to \nyour ~/.bash_profile and re-login. \nalias ..=\"cd ..\" \nalias ..2=\"cd ../..\" \nalias ..3=\"cd ../../..\" \nalias ..4=\"cd ../../../..\" \nalias ..5=\"cd ../../../../..\" \n# cd /tmp/very/long/directory/structure/that/is/too/deep \n# ..4 \n[Note: use ..4 to go up 4 directory level] \n# pwd \n/tmp/very/long/directory/structure/ \nMethod 2: Navigate up the directory using only dots \nIn the example below, ….. (five dots) is used to go up 4 directory level. \nTyping 5 dots to go up 4 directory structure is really easy to remember, \nas when you type the first two dots, you are thinking “going up one \ndirectory”, after that every additional dot, is to go one level up.\n16\n"
},
{
"page_number": 17,
"text": "Linux 101 Hacks www.thegeekstuff.com\nSo, use …. (four dots) to go up 3 directory level and .. (two dots) to go \nup 1 directory level. Add the following alias to your ~/.bash_profile and \nre-login for the ….. (five dots) to work properly. \nalias ..=\"cd ..\" \nalias ...=\"cd ../..\" \nalias ....=\"cd ../../..\" \nalias .....=\"cd ../../../..\" \nalias ......=\"cd ../../../../..\" \n# cd /tmp/very/long/directory/structure/that/is/too/deep \n# ..... \n[Note: use ..... (five dots) to go up 4 directory level] \n# pwd \n/tmp/very/long/directory/structure/ \nMethod 3: Navigate up the directory using cd followed by \nconsecutive dots \n In the example below, cd….. (cd followed by five dots) is used to go up \n4 directory level. Making it 5 dots to go up 4 directory structure is really \neasy to remember, as when you type the first two dots, you are thinking \n“going up one directory”, after that every additional dot, is to go one \nlevel up. So, use cd…. (cd followed by four dots) to go up 3 directory \nlevel and cd… (cd followed by three dots) to go up 2 directory level. Add \nthe following alias to your ~/.bash_profile and re-login for the above \ncd….. (five dots) to work properly. \nalias cd..=\"cd ..\" \nalias cd...=\"cd ../..\" \nalias cd....=\"cd ../../..\" \nalias cd.....=\"cd ../../../..\" \nalias cd......=\"cd ../../../../..\" \n17\n"
},
{
"page_number": 18,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# cd /tmp/very/long/directory/structure/that/is/too/deep \n# cd..... \n[Note: use cd..... to go up 4 directory level] \n# pwd \n/tmp/very/long/directory/structure \nMethod 4: Navigate up the directory using cd followed by \nnumber \nIn the example below, cd4 (cd followed by number 4) is used to go up 4 \ndirectory level. \nalias cd1=\"cd ..\" \nalias cd2=\"cd ../..\" \nalias cd3=\"cd ../../..\" \nalias cd4=\"cd ../../../..\" \nalias cd5=\"cd ../../../../..\" \nHack 3. Perform mkdir and cd Using a Single \nCommand \nSometimes when you create a new directory, you may cd to the new \ndirectory immediately to perform some work as shown below. \n# mkdir -p /tmp/subdir1/subdir2/subdir3 \n# cd /tmp/subdir1/subdir2/subdir3 \n# pwd \n/tmp/subdir1/subdir2/subdir3 \n18\n"
},
{
"page_number": 19,
"text": "Linux 101 Hacks www.thegeekstuff.com\nWouldn’t it be nice to combine both mkdir and cd in a single command? \nAdd the following to the .bash_profile and re-login. \n# vi .bash_profile \nfunction mkdircd () { mkdir -p \"$@\" && eval cd \"\\\"\\$$#\\\"\"; \n} \nNow, perform both mkdir and cd at the same time using a single \ncommand as shown below: \n# mkdircd /tmp/subdir1/subdir2/subdir3 \n[Note: This creates the directory and cd to it \nautomatically] \n# pwd \n/tmp/subdir1/subdir2/subdir3 \nHack 4. Toggle Between Directories \nYou can toggle between the last two current directories using cd - as \nshown below. \n# cd /tmp/very/long/directory/structure/that/is/too/deep \n# cd /tmp/subdir1/subdir2/subdir3 \n# cd - \n# pwd \n/tmp/very/long/directory/structure/that/is/too/deep \n# cd - \n# pwd \n/tmp/subdir1/subdir2/subdir3 \n19\n"
},
{
"page_number": 20,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# cd - \n# pwd \n/tmp/very/long/directory/structure/that/is/too/deep \nHack 5. Manipulate Directory Stack\nYou can use directory stack to push directories into it and later pop \ndirectory from the stack. Following three commands are used in this \nexample. \n•\ndirs: Display the directory stack \n•\npushd: Push directory into the stack \n•\npopd: Pop directory from the stack and cd to it \nDirs will always print the current directory followed by the content of the \nstack. Even when the directory stack is empty, dirs command will still \nprint only the current directory as shown below. \n# popd \n-bash: popd: directory stack empty \n# dirs \n~ \n# pwd \n/home/ramesh \nHow to use pushd and popd? Let us first create some temporary \ndirectories and push them to the directory stack as shown below. \n# mkdir /tmp/dir1 \n# mkdir /tmp/dir2 \n# mkdir /tmp/dir3 \n# mkdir /tmp/dir4 \n20\n"
},
{
"page_number": 21,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# cd /tmp/dir1 \n# pushd . \n# cd /tmp/dir2 \n# pushd . \n# cd /tmp/dir3 \n# pushd . \n# cd /tmp/dir4 \n# pushd . \n# dirs \n/tmp/dir4 /tmp/dir4 /tmp/dir3 /tmp/dir2 /tmp/dir1 \n[Note: The first directory (/tmp/dir4) of the dir command \noutput is always the current directory and not the content \nfrom the stack.] \nAt this stage, the directory stack contains the following directories: \n/tmp/dir4 \n/tmp/dir3 \n/tmp/dir2 \n/tmp/dir1 \nThe last directory that was pushed to the stack will be at the top. When \nyou perform popd, it will cd to the top directory entry in the stack and \nremove it from the stack. As shown above, the last directory that was \npushed into the stack is /tmp/dir4. So, when we do a popd, it will cd to \nthe /tmp/dir4 and remove it from the directory stack as shown below. \n# popd \n21\n"
},
{
"page_number": 22,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# pwd \n/tmp/dir4 \n[Note: After the above popd, directory Stack Contains: \n/tmp/dir3 \n/tmp/dir2 \n/tmp/dir1] \n# popd \n# pwd \n/tmp/dir3 \n \n[Note: After the above popd, directory Stack Contains: \n/tmp/dir2 \n/tmp/dir1] \n# popd \n# pwd \n/tmp/dir2 \n[Note: After the above popd, directory Stack Contains: \n/tmp/dir1] \n# popd \n# pwd \n/tmp/dir1 \n[Note: After the above popd, directory Stack is empty!] \n# popd \n-bash: popd: directory stack empty \n22\n"
},
{
"page_number": 23,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 6. Automatically Correct Mistyped \nDirectory Names \nUse shopt -s cdspell to correct the typos in the cd command \nautomatically as shown below. If you are not good at typing and make \nlot of mistakes, this will be very helpful. \n# cd /etc/mall \n-bash: cd: /etc/mall: No such file or directory \n \n# shopt -s cdspell \n# cd /etc/mall \n# pwd \n/etc/mail \n[Note: By mistake, when I typed mall instead of mail, cd \ncorrected it automatically] \nAny Questions?\nDiscuss it here: 6 CD Command Hacks\n23\n"
},
{
"page_number": 24,
"text": "Linux 101 Hacks www.thegeekstuff.com\nChapter 2: Essential Linux \nCommands \nHack 7. Grep Command \ngrep command is used to search files for a specific text. This is \nincredibly powerful command with lots of options. \nSyntax: grep [options] pattern [files] \nHow can I find all lines matching a specific keyword on a \nfile? \nIn this example, grep looks for the text John inside /etc/passwd file and \ndisplays all the matching lines. \n# grep John /etc/passwd \njsmith:x:1082:1082:John Smith:/home/jsmith:/bin/bash \njdoe:x:1083:1083:John Doe:/home/jdoe:/bin/bash \nOption -v, will display all the lines except the match. In the example \nbelow, it displays all the records from /etc/password that doesn't match \nJohn. \nNote: There are several lines in the /etc/password that doesn’t contain \nthe word John. Only the first line of the output is shown below. \n# grep -v John /etc/passwd \njbourne:x:1084:1084:Jason Bourne:/home/jbourne:/bin/bash \nHow many lines matched the text pattern in a particular \nfile? \nIn the example below, it displays the total number of lines that contains \nthe text John in /etc/passwd file. \n24\n"
},
{
"page_number": 25,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# grep -c John /etc/passwd \n2 \nYou can also get the total number of lines that did not match the specific \npattern by passing option -cv. \n# grep -cv John /etc/passwd \n39 \nHow to search a text by ignoring the case? \nPass the option -i (ignore case), which will ignore the case while \nsearching. \n# grep -i john /etc/passwd \njsmith:x:1082:1082:John Smith:/home/jsmith:/bin/bash \njdoe:x:1083:1083:John Doe:/home/jdoe:/bin/bash \nHow do I search all subdirectories for a text matching a \nspecific pattern? \nUse option -r (recursive) for this purpose. In the example below, it will \nsearch for the text \"John\" by ignoring the case inside all the \nsubdirectories under /home/users. \nThis will display the output in the format of \"filename: line that matching \nthe pattern\". You can also pass the option -l, which will display only the \nname of the file that matches the pattern. \n# grep -ri john /home/users \n/home/users/subdir1/letter.txt:John, Thanks for your \ncontribution. \n/home/users/name_list.txt:John Smith \n/home/users/name_list.txt:John Doe \n# grep -ril john /root \n25\n"
},
{
"page_number": 26,
"text": "Linux 101 Hacks www.thegeekstuff.com\n/home/users/subdir1/letter.txt \n/home/users/name_list.txt \nAdditional Grep Examples: \nGet a Grip on the Grep! – 15 Practical Grep Command \nExamples \nThe Power of Z Commands – Zcat, Zless, Zgrep, Zdiff \nExamples\n7 Linux Grep OR, Grep AND, Grep NOT Operator Examples\nHack 8. Regular Expression in Grep\nRegular expressions are used to search and manipulate the text, based \non the patterns. Most of the Linux commands and programming \nlanguages use regular expression. \nThis hack explains how to use most frequently used reg-ex operators in \nGrep command. \nBeginning of line ( ^ ) \nIn grep command, caret Symbol ^ matches the expression at the start of \na line. In the following example, it displays all the line which starts with \nthe Nov 10. i.e All the messages logged on November 10. \n$ grep \"^Nov 10\" messages.1 \nNov 10 01:12:55 gs123 ntpd[2241]: time reset +0.177479 s \nNov 10 01:17:17 gs123 ntpd[2241]: synchronized to \nLOCAL(0), stratum 10 \nNov 10 01:18:49 gs123 ntpd[2241]: synchronized to \n15.1.13.13, stratum 3 \nNov 10 13:21:26 gs123 ntpd[2241]: time reset +0.146664 s \n26\n"
},
{
"page_number": 27,
"text": "Linux 101 Hacks www.thegeekstuff.com\nNov 10 13:25:46 gs123 ntpd[2241]: synchronized to \nLOCAL(0), stratum 10 \nNov 10 13:26:27 gs123 ntpd[2241]: synchronized to \n15.1.13.13, stratum 3 \nThe ^ matches the expression in the beginning of a line, only if it is the \nfirst character in a regular expression. ^N matches line beginning with \nN. \nEnd of the line ( $) \nCharacter $ matches the expression at the end of a line. The following \ncommand will help you to get all the lines which ends with the word \n“terminating”. \n$ grep \"terminating.$\" messages \nJul 12 17:01:09 cloneme kernel: Kernel log daemon \nterminating. \nOct 28 06:29:54 cloneme kernel: Kernel log daemon \nterminating. \nFrom the above output you can come to know when all the kernel log \nhas got terminated. Just like ^ matches the beginning of the line only if \nit is the first character, $ matches the end of the line only if it is the last \ncharacter in a regular expression. \nCount of empty lines ( ^$ ) \nUsing ^ and $ character you can find out the empty lines available in a \nfile. “^$” specifies empty line. \n$ grep -c \"^$\" messages anaconda.log \nmessages:0 \nanaconda.log:3 \nThe above commands displays the count of the empty lines available in \nthe messages and anaconda.log files. \n27\n"
},
{
"page_number": 28,
"text": "Linux 101 Hacks www.thegeekstuff.com\nSingle Character (.) \nThe special meta-character “.” (dot) matches any character except the \nend of the line character. Let us take the input file which has the content \nas follows. \n$ cat input \n1. first line \n2. hi hello \n3. hi zello how are you \n4. cello \n5. aello \n6. eello \n7. last line \nNow let us search for a word which has any single character followed by \nello. i.e hello, cello etc., \n$ grep \".ello\" input \n2. hi hello \n3. hi zello how are you \n4. cello \n5. aello \n6. eello \nIn case if you want to search for a word which has only 4 character you \ncan give grep -w “….” where single dot represents any single character. \nZero or more occurrence (*) \nThe special character “*” matches zero or more occurrence of the \nprevious character. For example, the pattern ’1*’ matches zero or more \n’1′. \nThe following example searches for a pattern “kernel: *” i.e kernel: and \nzero or more occurrence of space character. \n28\n"
},
{
"page_number": 29,
"text": "Linux 101 Hacks www.thegeekstuff.com\n $ grep \"kernel: *.\" * \nmessages.4:Jul 12 17:01:02 cloneme kernel: ACPI: PCI \ninterrupt for device 0000:00:11.0 disabled \nmessages.4:Oct 28 06:29:49 cloneme kernel: ACPI: PM-Timer \nIO Port: 0x1008 \nmessages.4:Oct 28 06:31:06 btovm871 kernel: sda: sda1 \nsda2 sda3 \nmessages.4:Oct 28 06:31:06 btovm871 kernel: sd 0:0:0:0: \nAttached scsi disk sda \n. \n. \nIn the above example it matches for kernel and colon symbol followed \nby any number of spaces/no space and “.” matches any single \ncharacter. \nAdditional Grep Reg-Ex Examples: \nRegular Expressions in Grep Command with 10 Examples – \nPart I\nAdvanced Regular Expressions in Grep Command with 10 \nExamples – Part II\nHack 9. Find Command \nfind is frequently used command to find files in the UNIX filesystem \nbased on numerous conditions. Let us review some practice examples of \nfind command. \nSyntax: find [pathnames] [conditions] \nHow to find files containing a specific word in its name? \nThe following command looks for all the files under /etc directory with \nmail in the filename. \n29\n"
},
{
"page_number": 30,
"text": "Linux 101 Hacks www.thegeekstuff.com\n # find /etc -name \"*mail*\" \nHow to find all the files greater than certain size? \nThe following command will list all the files in the system greater than \n100MB. \n# find / -type f -size +100M \nHow to find files that are not modified in the last x \nnumber of days? \nThe following command will list all the files that were modified more \nthan 60 days ago under the current directory. \n# find . -mtime +60 \nHow to find files that are modified in the last x number of \ndays? \nThe following command will list all the files that were modified in the last \ntwo days under the current directory. \n# find . –mtime -2 \nHow to delete all the archive files with extension *.tar.gz \nand greater than 100MB? \nPlease be careful while executing the following command as you don’t \nwant to delete the files by mistake. The best practice is to execute the \nsame command with ls –l to make sure you know which files will get \ndeleted when you execute the command with rm. \n# find / -type f -name *.tar.gz -size +100M -exec ls -l {} \n\\; \n# find / -type f -name *.tar.gz -size +100M -exec rm -f {} \n\\; \n30\n"
},
{
"page_number": 31,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHow to archive all the files that are not modified in the \nlast x number of days? \nThe following command finds all the files not modified in the last 60 \ndays under /home/jsmith directory and creates an archive files under \n/tmp in the format of ddmmyyyy_archive.tar. \n# find /home/jsmith -type f -mtime +60 | xargs tar -cvf \n/tmp/`date '+%d%m%Y'_archive.tar` \nAdditional Find Examples: \nMommy, I found it! — 15 Practical Linux Find Command \nExamples \nDaddy, I found it!, 15 Awesome Linux Find Command \nExamples (Part2)\nHack 10. Suppress Standard Output and Error \nMessage \nSometime while debugging a shell script, you may not want to see either \nthe standard output or standard error message. Use /dev/null as shown \nbelow for suppressing the output. \nSuppress standard output using > /dev/null \nThis will be very helpful when you are debugging shell scripts, where \nyou don’t want to display the echo statement and interested in only \nlooking at the error messages. \n# cat file.txt > /dev/null \n# ./shell-script.sh > /dev/null \n31\n"
},
{
"page_number": 32,
"text": "Linux 101 Hacks www.thegeekstuff.com\nSuppress standard error using 2> /dev/null \nThis is also helpful when you are interested in viewing only the standard \noutput and don’t want to view the error messages. \n# cat invalid-file-name.txt 2> /dev/null \n# ./shell-script.sh 2> /dev/null \nNote: One of the most effective ways to use this is in the crontab, \nwhere you can suppress the output and error message of a cron task as \nshown below. \n30 1 * * * command > /dev/null 2>&1 \nHack 11. Join Command \nJoin command combines lines from two files based on a common field. \nIn the example below, we have two files – employee.txt and salary.txt. \nBoth have employee-id as common field. So, we can use join command \nto combine the data from these two files using employee-id as shown \nbelow. \n$ cat employee.txt \n100 Jason Smith \n200 John Doe \n300 Sanjay Gupta \n400 Ashok Sharma \n$ cat bonus.txt \n100 $5,000 \n200 $500 \n300 $3,000 \n400 $1,250 \n32\n"
},
{
"page_number": 33,
"text": "Linux 101 Hacks www.thegeekstuff.com\n$ join employee.txt bonus.txt \n100 Jason Smith $5,000 \n200 John Doe $500 \n300 Sanjay Gupta $3,000 \n400 Ashok Sharma $1,250 \nHack 12. Change the Case \nConvert a file to all upper-case \n$ cat employee.txt \n100 Jason Smith \n200 John Doe \n300 Sanjay Gupta \n400 Ashok Sharma \n$ tr a-z A-Z < employee.txt \n100 JASON SMITH \n200 JOHN DOE \n300 SANJAY GUPTA \n400 ASHOK SHARMA \nConvert a file to all lower-case \n$ cat department.txt \n100 FINANCE \n200 MARKETING \n300 PRODUCT DEVELOPMENT \n400 SALES \n33\n"
},
{
"page_number": 34,
"text": "Linux 101 Hacks www.thegeekstuff.com\n$ tr A-Z a-z < department.txt \n100 finance \n200 marketing \n300 product development \n400 sales \nHack 13. Xargs Command \nxargs is a very powerful command that takes output of a command and \npass it as argument of another command. \nThe following are some practical examples on how to use xargs \neffectively. \n1. When you are trying to delete too many files using rm, you may get \nerror message: /bin/rm Argument list too long – Linux. Use xargs to avoid \nthis problem. \nfind ~ -name ‘*.log’ -print0 | xargs -0 rm -f \n2. Get a list of all the *.conf file under /etc/. There are different ways to \nget the same result. Following example is only to demonstrate the use of \nxargs. The output of the find command in this example is passed to the \nls –l one by one using xargs. \n# find /etc -name \"*.conf\" | xargs ls –l \n3. If you have a file with list of URLs that you would like to download, you \ncan use xargs as shown below. \n# cat url-list.txt | xargs wget –c \n \n4. Find out all the jpg images and archive it. \n34\n"
},
{
"page_number": 35,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# find / -name *.jpg -type f -print | xargs tar -cvzf \nimages.tar.gz \n5. Copy all the images to an external hard-drive. \n# ls *.jpg | xargs -n1 -i cp {} /external-hard-\ndrive/directory \nHack 14. Sort Command \nSort command sorts the lines of a text file. Following are several \npractical examples on how to use the sort command based on the \nfollowing sample text file that has employee information in the format: \nemployee_name:employee_id:department_name. \n$ cat names.txt \nEmma Thomas:100:Marketing \nAlex Jason:200:Sales \nMadison Randy:300:Product Development \nSanjay Gupta:400:Support \nNisha Singh:500:Sales \nSort a text file in ascending order \n$ sort names.txt \nAlex Jason:200:Sales \nEmma Thomas:100:Marketing \nMadison Randy:300:Product Development \nNisha Singh:500:Sales \nSanjay Gupta:400:Support \nSort a text file in descending order \n35\n"
},
{
"page_number": 36,
"text": "Linux 101 Hacks www.thegeekstuff.com\n$ sort -r names.txt \nSanjay Gupta:400:Support \nNisha Singh:500:Sales \nMadison Randy:300:Product Development \nEmma Thomas:100:Marketing \nAlex Jason:200:Sales \nSort a colon delimited text file on 2nd field (employee_id) \n$ sort -t: -k 2 names.txt \nEmma Thomas:100:Marketing \nAlex Jason:200:Sales \nMadison Randy:300:Product Development \nSanjay Gupta:400:Support \nNisha Singh:500:Sales \nSort a tab delimited text file on 3rd field (department_name) and \nsuppress duplicates \n$ sort -t: -u -k 3 names.txt \nEmma Thomas:100:Marketing \nMadison Randy:300:Product Development \nAlex Jason:200:Sales \nSanjay Gupta:400:Support \nSort the passwd file by the 3rd field (numeric userid) \n$ sort -t: -k 3n /etc/passwd | more \nroot:x:0:0:root:/root:/bin/bash \nbin:x:1:1:bin:/bin:/sbin/nologin \ndaemon:x:2:2:daemon:/sbin:/sbin/nologin \nadm:x:3:4:adm:/var/adm:/sbin/nologin \n36\n"
},
{
"page_number": 37,
"text": "Linux 101 Hacks www.thegeekstuff.com\nlp:x:4:7:lp:/var/spool/lpd:/sbin/nologin \nSort /etc/hosts file by ip-address\n$ sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n /etc/hosts \n127.0.0.1 localhost.localdomain localhost \n192.168.100.101 dev-db.thegeekstuff.com dev-db \n192.168.100.102 prod-db.thegeekstuff.com prod-db \n192.168.101.20 dev-web.thegeekstuff.com dev-web \n192.168.101.21 prod-web.thegeekstuff.com prod-web \nCombine sort with other commands \n•\nps –ef | sort : Sort the output of process list \n•\nls -al | sort +4n : List the files in the ascending order of the file-\nsize. i.e sorted by 5th filed and displaying smallest files first. \n•\nls -al | sort +4nr : List the files in the descending order of the \nfile-size. i.e sorted by 5th filed and displaying largest files first. \nHack 15. Uniq Command \nUniq command is mostly used in combination with sort command, as \nuniq removes duplicates only from a sorted file. i.e In order for uniq to \nwork, all the duplicate entries should be in the adjacent lines. The \nfollowing are some common examples. \n1. When you have an employee file with duplicate entries, you can do \nthe following to remove duplicates. \n$ sort namesd.txt | uniq \n$ sort –u namesd.txt \n37\n"
},
{
"page_number": 38,
"text": "Linux 101 Hacks www.thegeekstuff.com\n2. If you want to know how many lines are duplicates, do the following. \nThe first field in the following examples indicates how many duplicates \nwhere found for that particular line. So, in this example the lines \nbeginning with Alex and Emma were found twice in the namesd.txt file. \n$ sort namesd.txt | uniq –c \n 2 Alex Jason:200:Sales \n 2 Emma Thomas:100:Marketing \n 1 Madison Randy:300:Product Development \n 1 Nisha Singh:500:Sales \n 1 Sanjay Gupta:400:Support \n3. The following displays only the entries that are duplicates. \n$ sort namesd.txt | uniq –cd \n 2 Alex Jason:200:Sales \n 2 Emma Thomas:100:Marketing \nHack 16. Cut Command \nCut command can be used to display only specific columns from a text \nfile or other command outputs. \nThe following are some of the examples. \nDisplay the 1st field (employee name) from a colon delimited file \n$ cut -d: -f 1 names.txt \nEmma Thomas \nAlex Jason \nMadison Randy \nSanjay Gupta \nNisha Singh \n38\n"
},
{
"page_number": 39,
"text": "Linux 101 Hacks www.thegeekstuff.com\nDisplay 1st and 3rd field from a colon delimited file \n$ cut -d: -f 1,3 names.txt \nEmma Thomas:Marketing \nAlex Jason:Sales \nMadison Randy:Product Development \nSanjay Gupta:Support \nNisha Singh:Sales \nDisplay only the first 8 characters of every line in a file \n$ cut -c 1-8 names.txt \nEmma Tho \nAlex Jas \nMadison \nSanjay G \nNisha Si \nMisc Cut command examples \n•\ncut -d: -f1 /etc/passwd Displays the unix login names for all the \nusers in the system. \n•\nfree | tr -s ' ' | sed '/^Mem/!d' | cut -d\" \" -f2 Displays the \ntotal memory available on the system. \nHack 17. Stat Command \nStat command can be used either to check the status/properties of a \nsingle file or the filesystem. \nDisplay statistics of a file or directory. \n$ stat /etc/my.cnf \n File: `/etc/my.cnf' \n39\n"
},
{
"page_number": 40,
"text": "Linux 101 Hacks www.thegeekstuff.com\n Size: 346 Blocks: 16 IO Block: 4096 regular file \nDevice: 801h/2049d Inode: 279856 Links: 1 \nAccess: (0644/-rw-r--r--) Uid: (0/root) Gid: (0/root) \nAccess: 2009-01-01 02:58:30.000000000 -0800 \nModify: 2006-06-01 20:42:27.000000000 -0700 \nChange: 2007-02-02 14:17:27.000000000 -0800 \n$ stat /home/ramesh \n File: `/home/ramesh' \n Size: 4096 Blocks: 8 IO Block: 4096 \ndirectory \nDevice: 803h/2051d Inode: 5521409 Links: 7 \nAccess: (0755/drwxr-xr-x) Uid: (401/ramesh) Gid: \n(401/ramesh) \nAccess: 2009-01-01 12:17:42.000000000 -0800 \nModify: 2009-01-01 12:07:33.000000000 -0800 \nChange: 2009-01-09 12:07:33.000000000 -0800 \nDisplay the status of the filesystem using option –f \n$ stat -f / \n File: \"/\" \n ID: 0 Namelen: 255 Type: ext2/ext3 \nBlocks: Total: 2579457 Free: 2008027 Available: \n1876998 Size: 4096 \nInodes: Total: 1310720 Free: 1215892 \nAdditional Stat Examples:\nUnix Stat Command: How To Identify File Attributes\n40\n"
},
{
"page_number": 41,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 18. Diff Command \ndiff command compares two different files and reports the difference. \nThe output of the diff command is very cryptic and not straight forward \nto read. \nSyntax: diff [options] file1 file2 \nWhat was modified in my new file when compare to my old \nfile? \nThe option -w in the diff command will ignore the white space while \nperforming the comparison. \nIn the following diff output: \n•\nThe lines above ---, indicates the changes happened in first file in \nthe diff command (i.e name_list.txt). \n•\nThe lines below ---, indicates the changes happened to the \nsecond file in the diff command (i.e name_list_new.txt). The lines \nthat belong to the first file starts with < and the lines of second \nfile starts with >. \n# diff -w name_list.txt name_list_new.txt \n2c2,3 \n< John Doe \n--- \n> John M Doe \n> Jason Bourne \nAdditional Diff Examples:\nTop 4 File Difference Tools on Linux – Diff, Colordiff, \nWdiff, Vimdiff\n41\n"
},
{
"page_number": 42,
"text": "Linux 101 Hacks www.thegeekstuff.com\nVisual File Diff with Vimdiff – It Does Make a \nDifference!\nHack 19. Display Total Connect Time of Users \nAc command will display the statistics about the user’s connect time. \nConnect time for the current logged in user \nWith the option –d, it will break down the output for the individual days. \nIn this example, I’ve been logged in to the system for more than 6 hours \ntoday. On Dec 1st, I was logged in for about 1 hour. \n$ ac –d \nDec 1 total 1.08 \nDec 2 total 0.99 \nDec 3 total 3.39 \nDec 4 total 4.50 \nToday total 6.10 \nConnect time for all the users \nTo display connect time for all the users use –p as shown below. Please \nnote that this indicates the cumulative connect time for the individual \nusers. \n$ ac -p \n john 3.64 \n madison 0.06 \n sanjay 88.17 \n nisha 105.92 \n ramesh 111.42 \n total 309.21 \n42\n"
},
{
"page_number": 43,
"text": "Linux 101 Hacks www.thegeekstuff.com\nConnect time for a specific user \nTo get a connect time report for a specific user, execute the following: \n$ ac -d sanjay \nJul 2 total 12.85 \nAug 25 total 5.05 \nSep 3 total 1.03 \nSep 4 total 5.37 \nDec 24 total 8.15 \nDec 29 total 1.42 \nToday total 2.95 \nHack 20. Execute Commands in the \nBackground \nYou can use one of the 5 methods explained in this hack to execute a \nLinux command, or shell script in the background. \nMethod 1. Use & \nYou can execute a command (or shell script) as a background job by \nappending an ampersand to the command as shown below. \n$ ./my-shell-script.sh & \nMethod 2. Nohup \nAfter you execute a command (or shell script) in the background using \n&, if you logout from the session, the command will get killed. To avoid \nthat, you should use nohup as shown below. \n$ nohup ./my-shell-script.sh & \nMethod 3. Screen Command \nAfter you execute a command in the background using nohup and &, the \ncommand will get executed even after you logout. But, you cannot \n43\n"
},
{
"page_number": 44,
"text": "Linux 101 Hacks www.thegeekstuff.com\nconnect to the same session again to see exactly what is happening on \nthe screen. To do that, you should use screen command. \nLinux screen command offers the ability to detach a session that is \nrunning some process, and then attach it at a later time. When you \nreattach the session later, your terminals will be there exactly in the way \nyou left them earlier. \nMethod 4. At Command \nUsing at command you can schedule a job to run at a particular date \nand time. For example, to execute the backup script at 10 a.m \ntomorrow, do the following. \n$ at -f backup.sh 10 am tomorrow \nMethod 5. Watch Command\nTo execute a command continuously at a certain interval, use watch \ncommand as shown below. \n$ watch df -h \nAdditional Background Command Examples: \nBg, Fg, &, Ctrl-Z – 5 Examples to Manage Unix Background \nJobs\nUnix Nohup: Run a Command or Shell-Script Even after You \nLogout\nScreen Command Examples: Get Control of Linux / Unix \nTerminal\nat, atq, atrm, batch Commands using 9 Examples\n44\n"
},
{
"page_number": 45,
"text": "Linux 101 Hacks www.thegeekstuff.com\nRepeat Unix Commands or Shell-Scripts every N seconds\nHack 21. Sed Basics - Find and Replace Using \nRegEx \nThis hack explains how to use sed substitute command “s”. \nThe `s’ command is probably the most important in `sed’ and has a lot \nof different options. \nThe `s’ command attempts to match the pattern space against the \nsupplied REGEXP; if the match is successful, then that portion of the \npattern space which was matched is replaced with REPLACEMENT. \nSyntax: \n#sed 'ADDRESSs/REGEXP/REPLACEMENT/FLAGS' filename \n#sed 'PATTERNs/REGEXP/REPLACEMENT/FLAGS' filename \n•\ns is substitute command \n•\n/ is a delimiter \n•\nREGEXP is regular expression to match \n•\nREPLACEMENT is a value to replace \nFLAGS can be any of the following :\n•\ng Replace all the instance of REGEXP with REPLACEMENT \n•\nn Could be any number,replace nth instance of the REGEXP with \nREPLACEMENT. \n•\np If substitution was made, then prints the new pattern space. \n•\ni match REGEXP in a case-insensitive manner. \n•\nw file If substitution was made, write out the result to the given \nfile. \n45\n"
},
{
"page_number": 46,
"text": "Linux 101 Hacks www.thegeekstuff.com\n•\nWe can use different delimiters ( one of @ % ; : ) instead of / \nLet us first create thegeekstuff.txt file that will be used in all the \nexamples mentioned below. \n$ cat thegeekstuff.txt \n# Instruction Guides \n1. Linux Sysadmin, Linux Scripting etc. \n2. Databases - Oracle, mySQL etc. \n3. Security (Firewall, Network, Online Security etc) \n4. Storage in Linux \n5. Productivity (Too many technologies to explore, not \nmuch time available) \n# Additional FAQS \n6. Windows- Sysadmin, reboot etc. \nSubstitute Word “Linux” to “Linux-Unix” Using sed s// \nIn the example below, in the output line “1. Linux-Unix Sysadmin, Linux \nScripting etc” only first Linux is replaced by Linux-Unix. If no flags are \nspecified the first match of line is replaced. \n$ sed 's/Linux/Linux-Unix/' thegeekstuff.txt \n# Instruction Guides \n1. Linux-Unix Sysadmin, Linux Scripting etc. \n2. Databases - Oracle, mySQL etc. \n3. Security (Firewall, Network, Online Security etc) \n4. Storage in Linux-Unix \n5. Productivity (Too many technologies to explore, not \nmuch time available) \n# Additional FAQS \n6. Windows- Sysadmin, reboot etc. \n46\n"
},
{
"page_number": 47,
"text": "Linux 101 Hacks www.thegeekstuff.com\nSubstitute all Appearances of a Word Using sed s//g \nThe below sed command replaces all occurrences of Linux to Linux-Unix \nusing global substitution flag “g”. \n$ sed 's/Linux/Linux-Unix/g' thegeekstuff.txt \n# Instruction Guides \n1. Linux-Unix Sysadmin, Linux-Unix Scripting etc. \n2. Databases - Oracle, mySQL etc. \n3. Security (Firewall, Network, Online Security etc) \n4. Storage in Linux-Unix \n5. Productivity (Too many technologies to explore, not \nmuch time available) \n# Additional FAQS \n6. Windows- Sysadmin, reboot etc. \nSubstitute Only 2nd Occurrence of a Word Using sed s//2 \nIn the example below, in the output line “1. Linux Sysadmin, Linux-Unix \nScripting etc.” only 2nd occurrence of Linux is replaced by Linux-Unix. \n$ sed 's/Linux/Linux-Unix/2' thegeekstuff.txt \n# Instruction Guides \n1. Linux Sysadmin, Linux-Unix Scripting etc. \n2. Databases - Oracle, mySQL etc. \n3. Security (Firewall, Network, Online Security etc) \n4. Storage in Linux \n5. Productivity (Too many technologies to explore, not \nmuch time available) \n# Additional FAQS \n6. Windows- Sysadmin, reboot etc. \n4. Write Changes to a File and Print the Changes Using sed \ns//gpw \nThe example below has substitution with three flags. It substitutes all \nthe occurrence of Linux to Linux-Unix and prints the substituted output \nas well as written the same to the given the file. \n47\n"
},
{
"page_number": 48,
"text": "Linux 101 Hacks www.thegeekstuff.com\n$ sed -n 's/Linux/Linux-Unix/gpw output' thegeekstuff.txt \n1. Linux-Unix Sysadmin, Linux-Unix Scripting etc. \n4. Storage in Linux-Unix \n$ cat output \n1. Linux-Unix Sysadmin, Linux-Unix Scripting etc. \n4. Storage in Linux-Unix \n5. Substitute Only When the Line Matches with the Pattern \nUsing sed \nIn this example, if the line matches with the pattern “-”, then it replaces \nall the characters from “-” with the empty. \n$ sed '/\\-/s/\\-.*//g' thegeekstuff.txt \n# Instruction Guides \n1. Linux Sysadmin, Linux Scripting etc. \n2. Databases \n3. Security (Firewall, Network, Online Security etc) \n4. Storage in Linux \n5. Productivity (Too many technologies to explore, not \nmuch time available) \n# Additional FAQS \n6. Windows \nDelete Last X Number of Characters From Each Line Using \nsed \nThis sed example deletes last 3 characters from each line. \n$ sed 's/...$//' thegeekstuff.txt \n# Instruction Gui \n1. Linux Sysadmin, Linux Scripting e \n2. Databases - Oracle, mySQL e \n3. Security (Firewall, Network, Online Security e \n48\n"
},
{
"page_number": 49,
"text": "Linux 101 Hacks www.thegeekstuff.com\n4. Storage in Li \n5. Productivity (Too many technologies to explore, not \nmuch time availab \n# Additional F \n6. Windows- Sysadmin, reboot e \nEliminate Comments Using sed \nDelete all the comment lines from a file as shown below using sed \ncommand. \n$ sed -e 's/#.*//' thegeekstuff.txt \n1. Linux Sysadmin, Linux Scripting etc. \n2. Databases - Oracle, mySQL etc. \n3. Security (Firewall, Network, Online Security etc) \n4. Storage in Linux \n5. Productivity (Too many technologies to explore, not \nmuch time available) \n6. Windows- Sysadmin, reboot etc. \n8. Eliminate Comments and Empty Lines Using sed \nIn the following example, there are two commands separated by ‘;’ \nFirst command replaces the lines starting with the # to the blank lines \nSecond command deletes the empty lines. \n$ sed -e 's/#.*//;/^$/d' thegeekstuff.txt \n1. Linux Sysadmin, Linux Scripting etc. \n2. Databases - Oracle, mySQL etc. \n3. Security (Firewall, Network, Online Security etc) \n4. Storage in Linux \n49\n"
},
{
"page_number": 50,
"text": "Linux 101 Hacks www.thegeekstuff.com\n5. Productivity (Too many technologies to explore, not \nmuch time available) \n6. Windows- Sysadmin, reboot etc. \n9. Convert DOS newlines (CR/LF) to Unix format Using sed \nEliminate HTML Tags from file Using sed \nIn this example, the regular expression given in the sed command \nmatches the html tags and replaces with the empty. \n$ sed -e 's/<[^>]*>//g' \nThis is an example. \nThis is an example. \nAny Questions?\nDiscuss it here: Sed Tutorial: Find and Replace Text \nInside a File Using RegEx\nAdditional Sed Substitution Examples:\nAdvanced Sed Substitution Examples\nHack 22: Awk Introduction – Print Examples \nThis hack explains the fundamental awk working methodology along \nwith 7 practical awk print examples. \nAwk Introduction and Printing Operations \nAwk is a programming language which allows easy manipulation of \nstructured data and the generation of formatted reports. Awk stands for \nthe names of its authors “Aho, Weinberger, and Kernighan” \n50\n"
},
{
"page_number": 51,
"text": "Linux 101 Hacks www.thegeekstuff.com\nThe Awk is mostly used for pattern scanning and processing. It searches \none or more files to see if they contain lines that matches with the \nspecified patterns and then perform associated actions. \nSome of the key features of Awk are: \n•\nAwk views a text file as records and fields. \n•\nLike common programming language, Awk has variables, \nconditionals and loops \n•\nAwk has arithmetic and string operators. \n•\nAwk can generate formatted reports \n•\nAwk reads from a file or from its standard input, and outputs to \nits standard output. Awk does not get along with non-text files. \nSyntax: \nawk '/search pattern1/ {Actions} \n /search pattern2/ {Actions}' file \nIn the above awk syntax: \n•\nsearch pattern is a regular expression. \n•\nActions – statement(s) to be performed. \n•\nseveral patterns and actions are possible in Awk. \n•\nfile – Input file. \n•\nSingle quotes around program is to avoid shell not to interpret \nany of its special characters. \nAwk Working Methodology \n1.\nAwk reads the input files one line at a time. \n2.\nFor each line, it matches with given pattern in the given order, if \nmatches performs the corresponding action. \n3.\nIf no pattern matches, no action will be performed. \n4.\nIn the above syntax, either search pattern or action are optional, \nBut not both. \n51\n"
},
{
"page_number": 52,
"text": "Linux 101 Hacks www.thegeekstuff.com\n5.\nIf the search pattern is not given, then Awk performs the given \nactions for each line of the input. \n6.\nIf the action is not given, print all that lines that matches with the \ngiven patterns which is the default action. \n7.\nEmpty braces with out any action does nothing. It wont perform \ndefault printing operation. \n8.\nEach statement in Actions should be delimited by semicolon. \nLet us create employee.txt file which has the following content, which \nwill be used in the examples mentioned below. \n$ cat employee.txt \n100 Thomas Manager Sales $5,000 \n200 Jason Developer Technology $5,500 \n300 Sanjay Sysadmin Technology $7,000 \n400 Nisha Manager Marketing $9,500 \n500 Randy DBA Technology $6,000 \nDefault behavior of Awk \nBy default Awk prints every line from the file. \n$ awk '{print;}' employee.txt \n100 Thomas Manager Sales $5,000 \n200 Jason Developer Technology $5,500 \n300 Sanjay Sysadmin Technology $7,000 \n400 Nisha Manager Marketing $9,500 \n500 Randy DBA Technology $6,000 \nIn the above example pattern is not given. So the actions are applicable \nto all the lines. \nAction print with out any argument prints the whole line by default. So it \nprints all the lines of the file with out fail. Actions has to be enclosed \nwith in the braces. \n52\n"
},
{
"page_number": 53,
"text": "Linux 101 Hacks www.thegeekstuff.com\nPrint the lines which matches with the pattern. \n$ awk '/Thomas/ \n> /Nisha/' employee.txt \n100 Thomas Manager Sales $5,000 \n400 Nisha Manager Marketing $9,500 \nIn the above example it prints all the line which matches with the \n‘Thomas’ or ‘Nisha’. It has two patterns. Awk accepts any number of \npatterns, but each set (patterns and its corresponding actions) has to be \nseparated by newline. \nPrint only specific field\nAwk has number of built in variables. For each record i.e line, it splits the \nrecord delimited by whitespace character by default and stores it in the \n$n variables. If the line has 4 words, it will be stored in $1, $2, $3 and \n$4. $0 represents whole line. NF is a built in variable which represents \ntotal number of fields in a record. \n$ awk '{print $2,$5;}' employee.txt \nThomas $5,000 \nJason $5,500 \nSanjay $7,000 \nNisha $9,500 \nRandy $6,000 \n$ awk '{print $2,$NF;}' employee.txt \nThomas $5,000 \nJason $5,500 \nSanjay $7,000 \nNisha $9,500 \nRandy $6,000 \nIn the above example $2 and $5 represents Name and Salary \nrespectively. We can get the Salary using $NF also, where $NF \nrepresents last field. In the print statement ‘,’ is a concatenator. \n53\n"
},
{
"page_number": 54,
"text": "Linux 101 Hacks www.thegeekstuff.com\nInitialization and Final Action \nAwk has two important patterns which are specified by the keyword \ncalled BEGIN and END. \nSyntax: \nBEGIN { Actions} \n{ACTION} # Action for everyline in a file \nEND { Actions } \n•\n# is for comments in Awk \n•\nActions specified in the BEGIN section will be executed before \nstarts reading the lines from the input. \n•\nEND actions will be performed after completing the reading and \nprocessing the lines from the input. \n$ awk 'BEGIN {print \n\"Name\\tDesignation\\tDepartment\\tSalary\";} \n> {print $2,\"\\t\",$3,\"\\t\",$4,\"\\t\",$NF;} \n> END{print \"Report Generated\\n--------------\"; \n> }' employee.txt \nName Designation Department Salary \nThomas \n Manager \n Sales \n $5,000 \nJason \n Developer Technology $5,500 \nSanjay \n Sysadmin \n Technology $7,000 \nNisha \n Manager \n Marketing $9,500 \nRandy \n DBA \n Technology $6,000 \nReport Generated \n-------------- \nIn the above example, it prints headline and last file for the reports. \n54\n"
},
{
"page_number": 55,
"text": "Linux 101 Hacks www.thegeekstuff.com\nFind the employees who has employee id greater than 200 \n$ awk '$1 >200' employee.txt \n300 Sanjay Sysadmin Technology $7,000 \n400 Nisha Manager Marketing $9,500 \n500 Randy DBA Technology $6,000 \nIn the above example, first field ($1) is employee id. So if $1 is greater \nthan 200, then just do the default print action to print the whole line. \nPrint the list of employees in Technology department \nNow department name is available as a fourth field, so need to check if \n$4 matches with the string “Technology”, if yes print the line. \n$ awk '$4 ~/Technology/' employee.txt \n200 Jason Developer Technology $5,500 \n300 Sanjay Sysadmin Technology $7,000 \n500 Randy DBA Technology $6,000 \nOperator ~ is for comparing with the regular expressions. If it matches \nthe default action i.e print whole line will be performed. \nPrint number of employees in Technology department \nThe below example, checks if the department is Technology, if it is yes, \nin the Action, just increment the count variable, which was initialized \nwith zero in the BEGIN section. \n$ awk 'BEGIN { count=0;} \n$4 ~ /Technology/ { count++; } \nEND { print \"Number of employees in Technology Dept \n=\",count;}' employee.txt \nNumber of employees in Tehcnology Dept = 3 \n55\n"
},
{
"page_number": 56,
"text": "Linux 101 Hacks www.thegeekstuff.com\nThen at the end of the process, just print the value of count which gives \nyou the number of employees in Technology department. \nAny Questions?\nDiscuss it here: Awk Introduction Tutorial – 7 Awk Print \nExamples\nAdditional Awk Examples:\nUnderstand Awk Variables with 3 Practical Examples\n8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, \nNR, NF, FILENAME, FNR \n7 Powerful Awk Operators Examples (Unary, Binary, \nArithmetic, String, Assignment, Conditional, Reg-Ex Awk \nOperators) \nAWK Arrays Explained with 5 Practical Examples\nHack 23. Vim Editor Navigation Fundamentals \nNavigation is a vital part of text editing. To be very productive, you \nshould be aware of all possible navigation shortcuts in your editor.\nThis hack explains the following 8 Vi / Vim navigation options. \n1.\nLine navigation \n2.\nScreen navigation \n3.\nWord navigation \n4.\nSpecial navigation \n5.\nParagraph navigation \n6.\nSearch navigation \n56\n"
},
{
"page_number": 57,
"text": "Linux 101 Hacks www.thegeekstuff.com\n7.\nCode navigation \n8.\nNavigation from command line \nLine Navigation \nFollowing are the four navigation that can be done line by line. \n•\nk – navigate upwards \n•\nj – navigate downwards \n•\nl – navigate right side \n•\nh – navigate left side \nBy using the repeat factor in VIM we can do this operation for N times. \nFor example, when you want to go down by 10 lines, then type “10j”. \nWithin a line if you want to navigate to different position, you have 4 \nother options. \n•\n0 – go to the starting of the current line. \n•\n^ – go to the first non blank character of the line. \n•\n$ – go to the end of the current line. \n•\ng_ – go to the last non blank character of the line. \nScreen Navigation \nFollowing are the three navigation which can be done in relation to text \nshown in the screen. \n•\nH – Go to the first line of current screen. \n•\nM – Go to the middle line of current screen. \n•\nL – Go to the last line of current screen. \n•\nctrl+f – Jump forward one full screen. \n•\nctrl+b – Jump backwards one full screen \n•\nctrl+d – Jump forward (down) a half screen \n•\nctrl+u – Jump back (up) one half screen \n57\n"
},
{
"page_number": 58,
"text": "Linux 101 Hacks www.thegeekstuff.com\nSpecial Navigation \nYou may want to do some special navigation inside a file, which are: \n•\nN% – Go to the Nth percentage line of the file. \n•\nNG – Go to the Nth line of the file. \n•\nG – Go to the end of the file. \n•\n`” – Go to the position where you were in NORMAL MODE while \nlast closing the file. \n•\n`^ – Go to the position where you were in INSERT MODE while \nlast closing the file. \n•\ng – Go to the beginning of the file. \nWord Navigation \nYou may want to do several navigation in relation to the words, such as: \n•\ne – go to the end of the current word. \n•\nE – go to the end of the current WORD. \n•\nb – go to the previous (before) word. \n•\nB – go to the previous (before) WORD. \n•\nw – go to the next word. \n•\nW – go to the next WORD. \nWORD – WORD consists of a sequence of non-blank characters, \nseparated with white space. \nword – word consists of a sequence of letters, digits and underscores. \nExample to show the difference between WORD and word \n•\n192.168.1.1 – single WORD \n•\n192.168.1.1 – seven words. \nParagraph Navigation \n58\n"
},
{
"page_number": 59,
"text": "Linux 101 Hacks www.thegeekstuff.com\n•\n{ – Go to the beginning of the current paragraph. By pressing \n{ again and again move to the previous paragraph beginnings. \n•\n} – Go to the end of the current paragraph. By pressing } again \nand again move to the next paragraph end, and again. \nSearch Navigation \n•\n/i – Search for a pattern which will you take you to the next \noccurrence of it. \n•\n?i – Search for a pattern which will you take you to the previous \noccurrence of it. \n•\n* - Go to the next occurrence of the current word under the \ncursor. \n•\n# - Go to the previous occurrence of the current word under the \ncursor. \nCode Navigation \n•\n% – Go to the matching braces, or parenthesis inside code. \nNavigation from Command Line \nVim +N filename: Go to the Nth line of the file after opening it. \nvim +10 /etc/passwd \nVim +/pattern filename: Go to the particular pattern’s line inside the file, \nfirst occurrence from first. In the following example, it will open the \nREADME file and jump to the first occurrence of the word “install”. \nvim +/install README \nVim +?patten filename: Go to the particular pattern’s line inside the file, \nfirst occurrence from last. In the following example, it will open the \nREADME file and jump to the last occurrence of the word “bug”. \nvim +?bug README\n59\n"
},
{
"page_number": 60,
"text": "Linux 101 Hacks www.thegeekstuff.com\nAny Questions?\nDiscuss it here: 8 Essential Vim Editor Navigation \nFundamentals\nMore Vim Examples:\nVim search and replace – 12 powerful find and replace \nexamples. \nHow To add bookmarks inside the Vim editor\nHow To record and play inside the Vim editor\nCorrect spelling mistakes automatically inside the Vim \nEditor\nHack 24. Chmod Command Examples\nThis hack explains how to use symbolic representation with chmod. \nFollowing are the symbolic representation of three different roles: \n•\nu is for user, \n•\ng is for group, \n•\nand o is for others. \nFollowing are the symbolic representation of three different permissions: \n•\nr is for read permission, \n•\nw is for write permission, \n•\nx is for execute permission. \n \n60\n"
},
{
"page_number": 61,
"text": "Linux 101 Hacks www.thegeekstuff.com\nThe following are few examples on how to use the symbolic \nrepresentation on chmod. \nAdd single permission to a file/directory \nChanging permission to a single set. + symbol means adding \npermission. For example, do the following to give execute permission for \nthe user irrespective of anything else: \n$ chmod u+x filename \nAdd multiple permission to a file/directory \nUse comma to separate the multiple permission sets as shown below. \n$ chmod u+r,g+x filename \nRemove permission from a file/directory \nThe following example removes read and write permission for the user. \n$ chmod u-rx filename \nChange permission for all roles on a file/directory \nThe following example assigns execute privilege to user, group and \nothers (basically anybody can execute this file). \n$ chmod a+x filename \nMake permission for a file same as another file (using \nreference) \nIf you want to change a file permission same as another file, use the \nreference option as shown below. In this example, file2′s permission will \nbe set exactly same as file1′s permission. \n$ chmod --reference=file1 file2 \n61\n"
},
{
"page_number": 62,
"text": "Linux 101 Hacks www.thegeekstuff.com\nApply the permission to all the files under a directory \nrecursively \nUse option -R to change the permission recursively as shown below. \n$ chmod -R 755 directory-name/ \nChange execute permission only on the directories (files \nare not affected) \nOn a particular directory if you have multiple sub-directories and files, \nthe following command will assign execute permission only to all the \nsub-directories in the current directory (not the files in the current \ndirectory). \n$ chmod u+X * \nNote: If the files has execute permission already for either the group or \nothers, the above command will assign the execute permission to the \nuser.\nAny Questions?\nDiscuss it here: 7 Chmod Command Examples for Beginners\nAdditional chmod Examples:\nBeginners Guide to File and Directory Permissions \n( umask, chmod, read, write, execute )\nHack 25. View Multiple Log Files in One \nTerminal \nTypically you may open multiple terminals to view tail -f of multiple files. \nFor example, if you want to view Apache error_log and access_log at the \nsame time you may do the following in two different terminals. \n62\n"
},
{
"page_number": 63,
"text": "Linux 101 Hacks www.thegeekstuff.com\n \nOn one terminal: \n$ tail -f error_log \nOn another terminal: \n$ tail -f access_log \nBut, wait! Wouldn’t it be nice if you can execute multiple unix tail \ncommand in single terminal using one of the following methods? \n$ multi-tail.sh error_log access_log \n(or) \n$ tail -f /var/log/syslog -f /var/log/auth.log \nThis hack explains two methods on how to execute multiple Linux tail -f \nat the same time in single terminal. \nMethod 1: Custom Shell Script (with Unix tail command) \nCreate the multitail.sh as shown below. \n$ vi multi-tail.sh \n#!/bin/sh \n# When this exits, exit all back ground process also. \ntrap 'kill $(jobs -p)' EXIT \n# iterate through the each given file names, \nfor file in \"$@\" \ndo \n63\n"
},
{
"page_number": 64,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# show tails of each in background. \ntail -f $file & \ndone \n# wait .. until CTRL+C \nwait \nNow, open multiple files using this new shell script as shown below. \n$ ./multi-tail.sh error_log access_log \nMethod 2: Standard Linux tail command \nThe latest version of the Unix tail command supports multiple -f as \nshown below. \n$ tail -f /var/log/syslog -f /var/log/auth.log \nAny Questions?\nDiscuss it here: 3 Methods To View tail -f output of \nMultiple Log Files in One Terminal\nHack 26. Less Command\nI personally prefer to use less command to view files (instead of opening \nthe file to view in an editor).\nLess is similar to more command, but less allows both forward and \nbackward movements. Moreover, less don’t require to load the whole file \nbefore viewing. Try opening a large log file in Vim editor and less — \nyou’ll see the speed difference. \n64\n"
},
{
"page_number": 65,
"text": "Linux 101 Hacks www.thegeekstuff.com\nThe navigation keys in less command are similar to Vim editor. This hack \nexplains less command navigation and other operations which will make \nyou a better command line warrior. \nSearch Navigation \nOnce you’ve opened a log file (or any file) using less file-name, use the \nfollowing keys to search. Please note that the match will be highlighted \nautomatically by default. \nUse the following shortcut for the less command forward search :\n•\n/ – search for a pattern which will take you to the next \noccurrence. \n•\nn – for next match in forward \n•\nN – for previous match in backward \nUse the following shortcut for the less command backward search :\n•\n? – search for a pattern which will take you to the previous \noccurrence. \n•\nn – for next match in backward direction \n•\nN – for previous match in forward direction \nTip: If you don't bother about which direction the search is happening, \nand you want to search file path, or URL, such as “/home/ramesh/”, you \ncan use backward search (?pattern) which will be handy as you don’t \nwant to escape slashes each time. \nSearch Path \nIn forward: /\\/home\\/ramesh\\/ \nIn backward: ?/home/ramesh/ \nScreen Navigation \nUse the following screen navigation commands while viewing large log \nfiles. \n•\n CTRL+F – forward one window \n65\n"
},
{
"page_number": 66,
"text": "Linux 101 Hacks www.thegeekstuff.com\n•\nCTRL+B – backward one window \n•\nCTRL+D – forward half window \n•\nCTRL+U – backward half window \nLine navigation \nIn a smaller chunk of data, where you want to locate particular error, \nyou may want to navigate line by line using these keys: \n•\nj – navigate forward by one line \n•\nk – navigate backward by one line \nOther Navigations \nThe following are other navigation operations that you can use inside \nthe less pager. \n•\nG – go to the end of file \n•\ng – go to the start of file \n•\nq or ZZ – exit the less pager \nSimulate tail -f inside less pager – Press F \nOnce you’ve opened a file using less command, any content that is \nappended to the file after that will not be displayed automatically. \nHowever, you can press F less command will show the status ‘waiting for \ndata‘. This is as similar to ‘tail -f’. \nCount magic \nSimilar to Vim editor navigation command, you can give 10j to scroll 10 \nlines down, or 10k to go up by 10 lines. \n•\n10j – 10 lines forward. \n•\n10k – 10 lines backward. \n•\nCTRL+G – show the current file name along with line, byte and \npercentage statistics. \n66\n"
},
{
"page_number": 67,
"text": "Linux 101 Hacks www.thegeekstuff.com\nOther useful Less Command Operations \n•\nv – using the configured editor edit the current file. \n•\nh – summary of less commands \n•\n&pattern – display only the matching lines, not all. \nMarked navigation \nWhen you are viewing a large log file using less command, you can mark \na particular position and return back to that place again by using that \nmark. \n•\nma – mark the current position with the letter ‘a’, \n•\n‘a – go to the marked position ‘a’. \nMultiple file paging \nMethod 1: You can open multiple files by passing the file names as \narguments. \n$ less file1 file2 \nMethod 2: While you are viewing file1, use :e to open the file2 as shown \nbelow.\n $ less file1 \n:e file2 \nNavigation across files: When you opened more than two files ( for e.g – \nless * ), use the following keys to navigate between files. \n•\n:n – go to the next file. \n•\n:p – go to the previous file.\nAny Questions?\n67\n"
},
{
"page_number": 68,
"text": "Linux 101 Hacks www.thegeekstuff.com\nDiscuss it here: Less Command: 10 Tips for Effective \nNavigation\nAdditional Less Examples:\nOpen & View 10 Different File Types with Linux Less \nCommand\nHack 27. Wget Examples \nwget utility is the best option to download files from internet. wget can \npretty much handle all complex download situations including large file \ndownloads, recursive downloads, non-interactive downloads, multiple \nfile downloads etc., \nThis hack explains how to use wget for various download scenarios using \n15 awesome wget examples. \nDownload Single File with wget \nThe following example downloads a single file from internet and stores \nin the current directory. \n$ wget http://www.openss7.org/repos/tarballs/strx25-\n0.9.2.1.tar.bz2 \nWhile downloading it will show a progress bar with the following \ninformation: \n•\n%age of download completion (for e.g. 31% as shown below) \n•\nTotal amount of bytes downloaded so far (for e.g. 1,213,592 \nbytes as shown below) \n•\nCurrent download speed (for e.g. 68.2K/s as shown below) \n•\nRemaining time to download (for e.g. eta 34 seconds as shown \nbelow) \n68\n"
},
{
"page_number": 69,
"text": "Linux 101 Hacks www.thegeekstuff.com\nDownload in progress: \n$ wget http://www.openss7.org/repos/tarballs/strx25-\n0.9.2.1.tar.bz2 \nSaving to: `strx25-0.9.2.1.tar.bz2.1' \n31% [=================> 1,213,592 68.2K/s eta 34s \nDownload completed: \n$ wget http://www.openss7.org/repos/tarballs/strx25-\n0.9.2.1.tar.bz2 \nSaving to: `strx25-0.9.2.1.tar.bz2' \n100%[======================>] 3,852,374 76.8K/s in 55s \n2009-09-25 11:15:30 (68.7 KB/s) - `strx25-0.9.2.1.tar.bz2' \nsaved [3852374/3852374] \nDownload and Store With a Different File name Using \nwget -O \nBy default wget will pick the filename from the last word after last \nforward slash, which may not be appropriate always. \nWrong: Following example will download and store the file with name: \ndownload_script.php?src_id=7701 \n$ wget http://www.vim.org/scripts/download_script.php?\nsrc_id=7701 \nEven though the downloaded file is in zip format, it will get stored in the \nfile as shown below. \n$ ls \ndownload_script.php?src_id=7701 \n69\n"
},
{
"page_number": 70,
"text": "Linux 101 Hacks www.thegeekstuff.com\nCorrect: To correct this issue, we can specify the output file name using \nthe -O option as: \n$ wget -O taglist.zip \nhttp://www.vim.org/scripts/download_script.php?src_id=7701 \nSpecify Download Speed / Download Rate Using wget –\nlimit-rate \nWhile executing the wget, by default it will try to occupy full possible \nbandwidth. This might not be acceptable when you are downloading \nhuge files on production servers. So, to avoid that we can limit the \ndownload speed using the –limit-rate as shown below. \nIn the following example, the download speed is limited to 200k \n$ wget --limit-rate=200k \nhttp://www.openss7.org/repos/tarballs/strx25-\n0.9.2.1.tar.bz2 \nContinue the Incomplete Download Using wget -c \nRestart a download which got stopped in the middle using wget -c option \nas shown below. \n$ wget -c http://www.openss7.org/repos/tarballs/strx25-\n0.9.2.1.tar.bz2 \nThis is very helpful when you have initiated a very big file download \nwhich got interrupted in the middle. Instead of starting the whole \ndownload again, you can start the download from where it got \ninterrupted using option -c \nNote: If a download is stopped in middle, when you restart the \ndownload again without the option -c, wget will append .1 to the \nfilename automatically as a file with the previous name already exist. If \na file with .1 already exist, it will download the file with .2 at the end. \n70\n"
},
{
"page_number": 71,
"text": "Linux 101 Hacks www.thegeekstuff.com\nDownload in the Background Using wget -b \nFor a huge download, put the download in background using wget option \n-b as shown below. \n$ wget -b http://www.openss7.org/repos/tarballs/strx25-\n0.9.2.1.tar.bz2 \nContinuing in background, pid 1984. \nOutput will be written to `wget-log'. \nIt will initiate the download and gives back the shell prompt to you. You \ncan always check the status of the download using tail -f as shown \nbelow. \n$ tail -f wget-log \nSaving to: `strx25-0.9.2.1.tar.bz2.4' \n 0K ...... ........ ......... .......... 1% 65.5K 57s \n 150K .......... ............. .......... 5% 86.6K 45s \n 250K .......... ............. .......... 7% 182M 46s \n 300K .......... ............. .......... 9% 57.9K 47s \nMask User Agent and Display wget like Browser Using \nwget –user-agent \nSome websites can disallow you to download its page by identifying that \nthe user agent is not a browser. So you can mask the user agent by \nusing –user-agent options and show wget like a browser as shown below. \n $ wget --user-agent=\"Mozilla/5.0 (X11; U; Linux i686; en-\nUS; rv:1.9.0.3) Gecko/2008092416 Firefox/3.0.3\" URL-TO-\nDOWNLOAD \nTest Download URL Using wget –spider \nWhen you are going to do scheduled download, you should check \nwhether download will happen fine or not at scheduled time. To do so, \ncopy the line exactly from the schedule, and then add –spider option to \ncheck. \n71\n"
},
{
"page_number": 72,
"text": "Linux 101 Hacks www.thegeekstuff.com\n$ wget --spider DOWNLOAD-URL \nIf the URL given is correct, it will say \n$ wget --spider download-url \nSpider mode enabled. Check if remote file exists. \nHTTP request sent, awaiting response... 200 OK \nLength: unspecified [text/html] \nRemote file exists and could contain further links, \nbut recursion is disabled -- not retrieving. \nThis ensures that the downloading will get success at the scheduled \ntime. But when you had give a wrong URL, you will get the following \nerror. \n$ wget --spider download-url \nSpider mode enabled. Check if remote file exists. \nHTTP request sent, awaiting response... 404 Not Found \nRemote file does not exist -- broken link!!! \nYou can use the spider option under following scenarios: \n•\nCheck before scheduling a download. \n•\nMonitoring whether a website is available or not at certain \nintervals. \n•\nCheck a list of pages from your bookmark, and find out which \npages are still exists. \nIncrease Total Number of Retry Attempts Using wget –tries \nIf the internet connection has problem, and if the download file is large \nthere is a chance of failures in the download. By default wget retries 20 \ntimes to make the download successful. \n72\n"
},
{
"page_number": 73,
"text": "Linux 101 Hacks www.thegeekstuff.com\nIf needed, you can increase retry attempts using –tries option as shown \nbelow. \n$ wget --tries=75 DOWNLOAD-URL \nDownload Multiple Files / URLs Using Wget -i \nFirst, store all the download files or URLs in a text file as: \n$ cat > download-file-list.txt \nURL1 \nURL2 \nURL3 \nURL4 \nNext, give the download-file-list.txt as argument to wget using -i option \nas shown below. \n$ wget -i download-file-list.txt \nDownload a Full Website Using wget –mirror \nFollowing is the command line which you want to execute when you \nwant to download a full website and made available for local viewing. \n$ wget --mirror -p --convert-links -P ./LOCAL-DIR WEBSITE-\nURL \n•\n–mirror : turn on options suitable for mirroring. \n•\n-p : download all files that are necessary to properly display a \ngiven HTML page. \n•\n–convert-links : after the download, convert the links in document \nfor local viewing. \n•\n-P ./LOCAL-DIR : save all the files and directories to the specified \ndirectory. \n73\n"
},
{
"page_number": 74,
"text": "Linux 101 Hacks www.thegeekstuff.com\nReject Certain File Types while Downloading Using wget –\nreject \nYou have found a website which is useful, but don’t want to download \nthe images you can specify the following. \n$ wget --reject=gif WEBSITE-TO-BE-DOWNLOADED \nLog messages to a log file instead of stderr Using wget -o \nWhen you wanted the log to be redirected to a log file instead of the \nterminal. \n$ wget -o download.log DOWNLOAD-URL \nQuit Downloading When it Exceeds Certain Size Using \nwget -Q \nWhen you want to stop download when it crosses 5 MB you can use the \nfollowing wget command line. \n$ wget -Q5m -i FILE-WHICH-HAS-URLS \nNote: This quota will not get effect when you do a download a single \nURL. That is irrespective of the quota size everything will get \ndownloaded when you specify a single file. This quota is applicable only \nfor recursive downloads. \nDownload Only Certain File Types Using wget -r -A \nYou can use this under following situations: \n•\n Download all images from a website \n•\nDownload all videos from a website \n•\nDownload all PDF files from a website \n$ wget -r -A.pdf http://url-to-webpage-with-pdfs/ \n74\n"
},
{
"page_number": 75,
"text": "Linux 101 Hacks www.thegeekstuff.com\nFTP Download With wget \nYou can use wget to perform FTP download as shown below. \nAnonymous FTP download using Wget \n$ wget ftp-url \nFTP download using wget with username and password authentication. \n$ wget --ftp-user=USERNAME --ftp-password=PASSWORD \nDOWNLOAD-URL\nAny Questions?\nDiscuss it here: Wget Download Guide With 15 Examples\n75\n"
},
{
"page_number": 76,
"text": "Linux 101 Hacks www.thegeekstuff.com\nChapter 3: SSH Commands and Tips\nHack 28. Debug SSH Client Session \nSometimes it is necessary to view debug messages to troubleshoot any \nSSH connection issues. pass -v (lowercase v) option to the ssh as shown \nbelow to view the ssh debug messages. \nExample without SSH client debug message: \n$ ssh -l jsmith remotehost.example.com \nwarning: Connecting to remotehost.example.com failed: No \naddress associated to the name \nExample with SSH client debug message: \n$ ssh -v -l jsmith remotehost.example.com \ndebug: SshConfig/sshconfig.c:2838/ssh2_parse_config_ext: \nMetaconfig parsing stopped at line 3. \ndebug: \nSshConfig/sshconfig.c:637/ssh_config_set_param_verbose: \nSetting variable ‘VerboseMode’ to ‘FALSE’. \ndebug: \nSshConfig/sshconfig.c:3130/ssh_config_read_file_ext: Read \n17 params from config file. \ndebug: Ssh2/ssh2.c:1707/main: User config file not found, \nusing defaults. (Looked for \n‘/home/jsmith/.ssh2/ssh2_config’) \ndebug: Connecting to remotehost.example.com, port 22… \n(SOCKS not used) \n76\n"
},
{
"page_number": 77,
"text": "Linux 101 Hacks www.thegeekstuff.com\nwarning: Connecting to remotehost.example.com failed: No \naddress associated to the name \nHack 29. Toggle SSH Session using SSH \nEscape Character \nWhen you’ve logged on to the remotehost using ssh from the localhost, \nyou may want to come back to the localhost to perform some activity \nand go back to remote host again. In this case, you don’t need to \ndisconnect the ssh session to the remote host. Instead, follow the steps \nbelow. \n1. Login to remotehost from localhost: \nlocalhost$ ssh -l jsmith remotehost \n2. Now you are connected to the remotehost: \nremotehost$ \n3. To come back to the localhost temporarily, type the escape character \n~ and Control-Z. \nWhen you type ~ you will not see that immediately on the screen until \nyou press and press enter. So, on the remotehost in a new \nline enter the following key strokes for the below to work: ~ \nremotehost$ ~^Z \n[1]+ Stopped ssh -l jsmith remotehost \nlocalhost$ \n4. Now you are back to the localhost and the ssh remotehost client \nsession runs as a typical UNIX background job, which you can check as \nshown below: \n77\n"
},
{
"page_number": 78,
"text": "Linux 101 Hacks www.thegeekstuff.com\nlocalhost$ jobs \n[1]+ Stopped ssh -l jsmith remotehost \n5. You can go back to the remote host ssh without entering the password \nagain by bringing the background ssh remotehost session job to \nforeground on the localhost. \nlocalhost$ fg %1 \nssh -l jsmith remotehost \nremotehost$ \nHack 30. Display SSH Session Statistics \nTo get some useful statistics about the current ssh session, do the \nfollowing. This works only on SSH2 client. \n1. Login to remotehost from localhost. \nlocalhost$ ssh -l jsmith remotehost \n2. On the remotehost, type ssh escape character ~ followed by s as \nshown below. This will display lot of useful statistics about the current \nSSH connection. \nremotehost$ [Note: The ~s is not visible on the command \nline when you type.] \n remote host: remotehost \n local host: localhost \n remote version: SSH-1.99-OpenSSH_3.9p1 \n local version: SSH-2.0-3.2.9.1 SSH Secure Shell \n compressed bytes in: 1506 \n uncompressed bytes in: 1622 \n78\n"
},
{
"page_number": 79,
"text": "Linux 101 Hacks www.thegeekstuff.com\n compressed bytes out: 4997 \n uncompressed bytes out: 5118 \n packets in: 15 \n packets out: 24 \n rekeys: 0 \n Algorithms: \n Chosen key exchange algorithm: diffie-hellman-\ngroup1-sha1 \n Chosen host key algorithm: ssh-dss \n Common host key algorithms: ssh-dss,ssh-rsa \n Algorithms client to server: \n Cipher: aes128-cbc \n MAC: hmac-sha1 \n Compression: zlib \n Algorithms server to client: \n Cipher: aes128-cbc \n MAC: hmac-sha1 \n Compression: zlib \nlocalhost$ \nAny questions?\nDiscuss it here: SSH Client commands\nHack 31. Change OpenSSH Security Options\nOpenSSH options are controlled through the /etc/ssh/sshd_config file. \nThis hack explains the 7 default options in sshd_config file that you \nshould change. \n79\n"
},
{
"page_number": 80,
"text": "Linux 101 Hacks www.thegeekstuff.com\nIn sshd_config, the lines that start with # are comments. For those \noptions that uses the default values, the sshd_config file contains a \ncommented line with the option and its default value. \nThis makes it easier for us, as we can see the OpenSSH option name and \nthe default value without having to lookup somewhere else. \nFor example, sshd_config file contains the following commented line. \nThis indicates that the PubkeyAuthentication option contains “yes” as \nthe default value. \n$ grep -i pubkey /etc/ssh/sshd_config \n#PubkeyAuthentication yes \nIf you like to change this, you should remove the comment and change \nthe value (from yes to no) as shown below. \n$ vi /etc/ssh/sshd_config \nPubkeyAuthentication no \nI showed the above only as an example. You don’t need to change the \ndefault value of PubkeyAuthentication option, as allowing public key \nauthentication is good. \nYou don’t need to modify any of the default values in the sshd_config file \nexcept the 7 options mentioned in this hack. \nDisable Root Login (PermitRootLogin) \nBy default you can ssh to the server as root. It is best not to allow root to \nlogin directly to the server. Instead, you should login to the system as \nyour account and then do ‘su -’ to login as root. \nIf you have multiple sysadmins in your organization, and if they all login \nto the server directly as root, you might not know which sysadmin \nlogged in as root. Instead, if you disable login as root, sysadmins are \n80\n"
},
{
"page_number": 81,
"text": "Linux 101 Hacks www.thegeekstuff.com\nforced to login as their account first, before they can do ‘su -’, this \nmakes the auditing easier. \nAdd the following entry to sshd_config to disable root to login to the \nserver directly. \n$ vi /etc/ssh/sshd_config \nPermitRootLogin no \nAllow Only Specific Users or Groups (AllowUsers \nAllowGroups) \nBy default anybody who is authenticated successfully are allowed to \nlogin. Instead you can restrict which users (or groups) you allow to login \nto the system. \nThis is helpful when you have created several user accounts on the \nsystem, but want only few of them to login. \nThis is also helpful when you are using NIS, openLDAP (or some other \nexternal system) for authentication. Every user in your company might \nhave account on NIS, OpenLDAP etc. But, on a specific server you want \nonly few of them to login. For example, on production system you want \nonly sysadmins to login. \nAdd the following entry to the sshd_config file to allow only specific \nusers to login to the system. In the example below only ramesh, john \nand jason can login to this system. Usernames should be separated by \nspace. \n$ vi /etc/ssh/sshd_config \nAllowUsers ramesh john jason \nAdd the following entry to the sshd_config file to allow only the users \nwho belong to a specific group to login. In the example below only users \nwho belong to sysadmin and dba group can login to the system. \n$ vi /etc/ssh/sshd_config \n81\n"
},
{
"page_number": 82,
"text": "Linux 101 Hacks www.thegeekstuff.com\nAllowGroups sysadmin dba \nDeny Specific Users or Groups (DenyUsers DenyGroups) \nInstead of allowing specific users (or groups), you can also deny specific \nusers or groups. \nAdd the following entry to the sshd_config file to deny specific users to \nlogin to the system. In the example below cvs, apache, jane cannot login \nto this system. Usernames should be separated by space. \n$ vi /etc/ssh/sshd_config \nDenyUsers cvs apache jane \nAdd the following entry to the sshd_config file to deny users who belong \nto a specific group to login. In the example below users who belong to \ndevelopers and qa group cannot login to the system. \n$ vi /etc/ssh/sshd_config \nDenyGroups developers qa \nNote: You can use combination of all the Allow and Deny directives. It is \nprocessed in this order: DenyUsers, AllowUsers, DenyGroups, and finally \nAllowGroups \nChange SSHD Port Number (Port) \nBy default ssh runs on port 22. Most of the attackers will check if a \nserver is open on port 22, and will randomly use brute force to login to \nthe server using several username and password combination. \nIf you change the port # to something different, others need to know \nexactly what port to use to login to the server using ssh. The example \nbelow uses port 222 for ssh. \n$ vi /etc/ssh/sshd_config \nPort 222 \n82\n"
},
{
"page_number": 83,
"text": "Linux 101 Hacks www.thegeekstuff.com\nFrom your logs (/var/log/secure), if you see lot of invalid logins using ssh \nfor accounts that don’t exist on your system, from the ip-address that \nyou don’t recognize, it might be some brute-force attack. Those kind of \nssh invalid login will stop, if you change the port number. \nPlease note that this causes little inconvenience to your team who login \nto the system, as they need to know both the ip-address and the port \nnumber. \nChange Login Grace Time (LoginGraceTime) \nWhen you ssh to a server, you have 2 minutes to login. If you don’t \nsuccessfully login within 2 minutes, ssh will disconnect. \n2 minutes time to login successfully is too much. You should consider \nchanging it to 30 seconds, or may be 1 minute. \nAdd the following entry to the sshd_config file to change the login grace \ntime from 2 minutes to 1 minute. \n$ vi /etc/ssh/sshd_config \nLoginGraceTime 1m \nRestrict the Interface (IP Address) to Login \n(ListenAddress) \nIf you have multiple interfaces on the server that are configured to \ndifferent ip-address, you might not want everybody to login to the server \nusing all those ip-address. \nLet us assume that you have the following 4 interfaces on the server: \n•\neth0 – 192.168.10.200 \n•\neth1 – 192.168.10.201 \n•\neth2 – 192.168.10.202 \n•\neth3 – 192.168.10.203 \n83\n"
},
{
"page_number": 84,
"text": "Linux 101 Hacks www.thegeekstuff.com\nBy default ssh will listen on all of the above ip-addresses. If you want \nusers to login only using ip-address 200 and 202, do the following in \nyour sshd_config \n$ vi /etc/ssh/sshd_config \nListenAddress 192.168.10.200 \nListenAddress 192.168.10.202 \nDisconnect SSH when no activity (ClientAliveInterval) \nOnce you’ve successfully logged in to the system, you might want to get \ndisconnected when there are no activities after x number of minutes. \nThis is basically idle timeout. \n \nIn Bash, you can achieve this using TMOUT variable. \nIn OpenSSH, this can be achieved by combining ClientAliveCountMax \nand ClientAliveInterval options in sshd_config file. \n•\nClientAliveCountMax – This indicates the total number of \ncheckalive message sent by the ssh server without getting any \nresponse from the ssh client. Default is 3. \n•\nClientAliveInterval – This indicates the timeout in seconds. After x \nnumber of seconds, ssh server will send a message to the client \nasking for response. Deafult is 0 (server will not send message to \nclient to check.). \nIf you want ssh client to exit (timeout) automatically after 10 minutes \n(600 seconds), modify the sshd_config file and set the following two \nparameters as shown below. \n$ vi /etc/ssh/sshd_config \nClientAliveInterval 600 \nClientAliveCountMax 0\n84\n"
},
{
"page_number": 85,
"text": "Linux 101 Hacks www.thegeekstuff.com\nAny Questions?\n \nDiscuss it here: 7 Default OpenSSH Security Options that \nYou Should Change\nHack 32. Transfer All PuTTY Sessions\nIf you want to connect from a Windows machine to a Linux server, you \nneed to use one of the SSH clients. PuTTY is hands-down the best SSH \nclient for Windows. It’s light-weight with a single putty.exe file and \nnothing else to install. \nIf you have not used PuTTY earlier, you may want to download PuTTY \nsoftware from the official PuTTY download page before exploring these \nPuTTY tricks. \nMove Putty sessions to another computer \nPuTTY stores all the session information in Windows registry. On the \nsource machine, export the PuTTY session registry information as shown \nbelow. \nC:> regedit /e \"%userprofile%\\desktop\\putty-registry.reg\" \nHKEY_CURRENT_USER\\Software\\Simontatham \nTransfer this putty-registry.reg file from source machine to destination \nmachine. \nOn the destination machine, import the PuTTY SSH session registry, by \nright mouse-click on the putty-registry.reg and click on ‘Merge’. This will \ntransfer all the PuTTY session information from one windows system to \nanother.\nDelete All PuTTY Sessions Together \nWhen you are swapping an old computer with a new computer, you may \nend-up transferring all PuTTY sessions to new computer. Once you’ve \n85\n"
},
{
"page_number": 86,
"text": "Linux 101 Hacks www.thegeekstuff.com\ntransferred all PuTTY sessions, execute “putty -cleanup” from the \ncommand line as shown below. \nC:>putty -cleanup \nThis will display a warning message. Click on ‘Yes’ to wipe-out all PuTTY \nsession and random seed files from the Windows registry. This is a better \nprocess to delete all saved PuTTY sessions from Windows registry \ninstead of deleting one-by-one from the PuTTY session list. \nMore PuTTY Tips:\nTurbocharge PuTTY with 12 Powerful Add-Ons\n10 Awesome PuTTY Tips and Tricks You Probably Didn’t \nKnow\nExtreme Makeover Using PuTTY Connection Manager\n86\n"
},
{
"page_number": 87,
"text": "Linux 101 Hacks www.thegeekstuff.com\nChapter 4: Date Manipulation \nHack 33. Set System Date and Time \nTo change the system date use: \n# date {mmddhhmiyyyy.ss} \n•\nmm – Month \n•\ndd – Date \n•\nhh – 24 hour format \n•\nmi – Minutes \n•\nyyyy – Year \n•\nss – seconds \nFor example, to set system date to Jan 31st 2009, 10:19 p.m, 53 \nseconds \n# date 013122192009.53 \nYou can also change system date using set argument as shown below. \n# date 013122192009.53 \n# date +%Y%m%d -s \"20090131\" \n# date -s \"01/31/2009 22:19:53\" \n# date -s \"31 JAN 2009 22:19:53\" \n# date set=\"31 JAN 2009 22:19:53\" \n87\n"
},
{
"page_number": 88,
"text": "Linux 101 Hacks www.thegeekstuff.com\nTo set the time only: \n# date +%T -s \"22:19:53\" \n# date +%T%p -s \"10:19:53PM\" \nHack 34. Set Hardware Date and Time \nBefore setting the hardware date and time, make sure the OS date and \ntime is set appropriately as shown in previous hack. \n \nSet the hardware date and time based on the system date as shown \nbelow: \n# hwclock –systohc \n# hwclock --systohc –utc \nUse hwclock without any parameter, to view the current hardware date \nand time: \n# hwclock \nCheck the clock file to verify whether the system is set for UTC: \n# cat /etc/sysconfig/clock \nZONE=\"America/Los_Angeles\" \nUTC=false \nARC=false \n88\n"
},
{
"page_number": 89,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 35. Display Date and Time in a Specific \nFormat \nThe following are different ways of displaying the current date and time \nin various formats: \n$ date \nThu Jan 1 08:19:23 PST 2009 \n$ date --date=\"now\" \nThu Jan 1 08:20:05 PST 2009 \n$ date --date=\"today\" \nThu Jan 1 08:20:12 PST 2009 \n \n$ date --date='1970-01-01 00:00:01 UTC +5 hours' +%s \n18001 \n$ date '+Current Date: %m/%d/%y%nCurrent Time:%H:%M:%S' \nCurrent Date: 01/01/09 \nCurrent Time:08:21:41 \n$ date +\"%d-%m-%Y\" \n01-01-2009 \n$ date +\"%d/%m/%Y\" \n01/01/2009 \n$ date +\"%A,%B %d %Y\" \nThursday,January 01 2009 \n89\n"
},
{
"page_number": 90,
"text": "Linux 101 Hacks www.thegeekstuff.com\nThe following are the different format options you can pass to the date \ncommand: \n•\n%D date (mm/dd/yy) \n•\n%d day of month (01..31) \n•\n%m month (01..12) \n•\n%y last two digits of year (00..99) \n•\n%a locale’s abbreviated weekday name (Sun..Sat) \n•\n%A locale’s full weekday name, variable length \n(Sunday..Saturday) \n•\n%b locale’s abbreviated month name (Jan..Dec) \n•\n%B locale’s full month name, variable length \n(January..December) \n•\n%H hour (00..23) \n•\n%I hour (01..12) \n•\n%Y year (1970…) \nHack 36. Display Past Date and Time \nThe following are various ways to display a past date and time: \n$ date --date='3 seconds ago' \nThu Jan 1 08:27:00 PST 2009 \n$ date --date=\"1 day ago\" \nWed Dec 31 08:27:13 PST 2008 \n$ date --date=\"1 days ago\" \nWed Dec 31 08:27:18 PST 2008 \n$ date --date=\"1 month ago\" \nMon Dec 1 08:27:23 PST 2008 \n90\n"
},
{
"page_number": 91,
"text": "Linux 101 Hacks www.thegeekstuff.com\n$ date --date=\"1 year ago\" \nTue Jan 1 08:27:28 PST 2008 \n$ date --date=\"yesterday\" \nWed Dec 31 08:27:34 PST 2008 \n$ date --date=\"10 months 2 day ago\" \nThu Feb 28 08:27:41 PST 2008 \nHack 37. Display Future Date and Time \nThe following examples shows how to display a future date and time. \n$ date \nThu Jan 1 08:30:07 PST 2009 \n$ date --date='3 seconds' \nThu Jan 1 08:30:12 PST 2009 \n$ date --date='4 hours' \nThu Jan 1 12:30:17 PST 2009 \n$ date --date='tomorrow' \nFri Jan 2 08:30:25 PST 2009 \n$ date --date=\"1 day\" \nFri Jan 2 08:30:31 PST 2009 \n$ date --date=\"1 days\" \nFri Jan 2 08:30:38 PST 2009 \n$ date --date=\"2 days\" \n91\n"
},
{
"page_number": 92,
"text": "Linux 101 Hacks www.thegeekstuff.com\nSat Jan 3 08:30:43 PST 2009 \n$ date --date='1 month' \nSun Feb 1 08:30:48 PST 2009 \n$ date --date='1 week' \nThu Jan 8 08:30:53 PST 2009 \n$ date --date=\"2 months\" \nSun Mar 1 08:30:58 PST 2009 \n$ date --date=\"2 years\" \nSat Jan 1 08:31:03 PST 2011 \n$ date --date=\"next day\" \nFri Jan 2 08:31:10 PST 2009 \n$ date --date=\"-1 days ago\" \nFri Jan 2 08:31:15 PST 2009 \n$ date --date=\"this Wednesday\" \nWed Jan 7 00:00:00 PST 2009 \n92\n"
},
{
"page_number": 93,
"text": "Linux 101 Hacks www.thegeekstuff.com\nChapter 5: PS1, PS2, PS3, PS4 and \nPROMPT_COMMAND\nHack 38. PS1 - Default Interaction Prompt \nThe default interactive prompt on your Linux can be modified as shown \nbelow to something useful and informative. In the following example, \nthe default PS1 was “\\s-\\v\\$”, which displays the shell name and the \nversion number. Let us change this default behavior to display the \nusername, hostname and current working directory name as shown \nbelow. \n-bash-3.2$ export PS1=\"\\u@\\h \\w> \" \nramesh@dev-db ~> cd /etc/mail \nramesh@dev-db /etc/mail> \n[Note: Prompt changed to \"username@hostname current-dir>\" \nformat] \nFollowing PS1 codes are used in this example: \n•\n\\u – Username \n•\n\\h – Hostname \n•\n\\w - Full pathname of current directory. Please note that when you \nare in the home directory, this will display only ~ as shown above \nNote that there is a space at the end in the value of PS1. Personally, I \nprefer a space at the end of the prompt for better readability. \nMake this setting permanent by adding export PS1=”\\u@\\h \\w> ” to \neither .bash_profile (or) .bashrc as shown below. \n93\n"
},
{
"page_number": 94,
"text": "Linux 101 Hacks www.thegeekstuff.com\nramesh@dev-db ~> vi ~/.bash_profile \nramesh@dev-db ~> vi ~/.bashrc \n[Note: Add export PS1=\"\\u@\\h \\w> \" to one of the above \nfiles] \nHack 39. PS2 - Continuation Interactive \nPrompt \nA very long command can be broken down to multiple lines by giving \\ at \nthe end of the line. The default interactive prompt for a multi-line \ncommand is “> “. Let us change this default behavior to display \n“continue->” by using PS2 environment variable as shown below. \nramesh@dev-db ~> myisamchk --silent --force --fast \n--update-state \\ \n> --key_buffer_size=512M --sort_buffer_size=512M \\ \n> --read_buffer_size=4M --write_buffer_size=4M \\ \n> /var/lib/mysql/bugs/*.MYI \n[Note: This uses the default \">\" for continuation prompt] \nramesh@dev-db ~> export PS2=\"continue-> \" \nramesh@dev-db ~> myisamchk --silent --force --fast \n--update-state \\ \ncontinue-> --key_buffer_size=512M \n--sort_buffer_size=512M \\ \ncontinue-> --read_buffer_size=4M --write_buffer_size=4M \\ \ncontinue-> /var/lib/mysql/bugs/*.MYI \n[Note: This uses the modified \"continue-> \" for \ncontinuation prompt] \n94\n"
},
{
"page_number": 95,
"text": "Linux 101 Hacks www.thegeekstuff.com\n I found it very helpful and easy to read, when I break my long \ncommands into multiple lines using \\. I have also seen others who don’t \nlike to break-up long commands. \nHack 40. PS3 - Prompt Used by Select \nCommand\nYou can define a custom prompt for the select loop inside a shell script, \nusing the PS3 environment variable, as explained below. \nShell script and output WITHOUT PS3: \nramesh@dev-db ~> cat ps3.sh \nselect i in mon tue wed exit \ndo \n case $i in \n mon) echo \"Monday\";; \n tue) echo \"Tuesday\";; \n wed) echo \"Wednesday\";; \n exit) exit;; \n esac \ndone \nramesh@dev-db ~> ./ps3.sh \n1) mon \n2) tue \n3) wed \n4) exit \n#? 1 \nMonday \n#? 4 \n95\n"
},
{
"page_number": 96,
"text": "Linux 101 Hacks www.thegeekstuff.com\n[Note: This displays the default \"#?\" for select command \nprompt] \n Shell script and output WITH PS3: \nramesh@dev-db ~> cat ps3.sh \nPS3=\"Select a day (1-4): \" \nselect i in mon tue wed exit \ndo \n case $i in \n mon) echo \"Monday\";; \n tue) echo \"Tuesday\";; \n wed) echo \"Wednesday\";; \n exit) exit;; \n esac \ndone \nramesh@dev-db ~> ./ps3.sh \n1) mon \n2) tue \n3) wed \n4) exit \nSelect a day (1-4): 1 \nMonday \nSelect a day (1-4): 4 \n[Note: This displays the modified \"Select a day (1-4):\" \nfor select command prompt] \n96\n"
},
{
"page_number": 97,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 41. PS4 - Prompt to Prefix Tracing \nOutput \nThe PS4 shell variable defines the prompt that gets displayed, when you \nexecute a shell script in debug mode (using set -x) as shown below. \nShell script and output WITHOUT PS4: \nramesh@dev-db ~> cat ps4.sh \nset -x \necho \"PS4 demo script\" \nls -l /etc/ | wc -l \ndu -sh ~ \nramesh@dev-db ~> ./ps4.sh \n ++ echo 'PS4 demo script' \nPS4 demo script \n++ ls -l /etc/ \n++ wc -l \n243 \n++ du -sh /home/ramesh \n48K /home/ramesh \n[Note: This displays the default \"++\" while tracing the \noutput using set -x] \nShell script and output WITH PS4: \nThe PS4 defined below in the ps4.sh has the following two codes: \n•\n$0 - indicates the name of script \n•\n$LINENO - displays the current line number within the script \nramesh@dev-db ~> cat ps4.sh \n97\n"
},
{
"page_number": 98,
"text": "Linux 101 Hacks www.thegeekstuff.com\nexport PS4='$0.$LINENO+ ' \nset -x \necho \"PS4 demo script\" \nls -l /etc/ | wc -l \ndu -sh ~ \nramesh@dev-db ~> ./ps4.sh \n../ps4.sh.3+ echo 'PS4 demo script' \nPS4 demo script \n../ps4.sh.4+ ls -l /etc/ \n../ps4.sh.4+ wc -l \n243 \n../ps4.sh.5+ du -sh /home/ramesh \n48K /home/ramesh \n[Note: This displays the modified \"{script-name}.{line-\nnumber}+\" while tracing the output using set -x] \nHack 42. PROMPT_COMMAND \nBash shell executes the content of the PROMPT_COMMAND just before \ndisplaying the PS1 variable. \nramesh@dev-db ~> export PROMPT_COMMAND=\"date +%H:%M:%S\" \n22:08:42 \nramesh@dev-db ~> \n[Note: This displays the PROMPT_COMMAND and PS1 output on \ndifferent lines] \nIf you want to display the value of PROMPT_COMMAND in the same line \nas the PS1, use the echo -n as shown below. \n98\n"
},
{
"page_number": 99,
"text": "Linux 101 Hacks www.thegeekstuff.com\nramesh@dev-db ~> export PROMPT_COMMAND=\"echo -n [$(date +\n%H:%M:%S)]\" \n[22:08:51]ramesh@dev-db ~> \n[Note: This displays the PROMPT_COMMAND and PS1 output on \nthe same line] \nAny Questions?\nDiscuss it here: Bash Shell: Take Control of PS1, PS2, \nPS3, PS4 and PROMPT_COMMAND\nHack 43. Customize Bash Prompt Using PS1\nDisplay username, hostname and basename of directory in \nthe prompt \nThe PS1 in this example displays following three information in the \nprompt: \n•\n\\u – Username \n•\n\\h – Hostname \n•\n\\W – Base name of the current working directory \n-bash-3.2$ export PS1=\"\\u@\\h \\W> \" \nramesh@dev-db ~> cd /etc/mail \nramesh@dev-db mail> \n99\n"
},
{
"page_number": 100,
"text": "Linux 101 Hacks www.thegeekstuff.com\nDisplay current time in the prompt \nIn the PS1 environment variable, you can directly execute any Linux \ncommand, by specifying in the format $(linux_command). In the \nfollowing example, the command $(date) is executed to display the \ncurrent time inside the prompt. \nramesh@dev-db ~> export PS1=\"\\u@\\h [\\$(date +%H:%M:%S)]> \" \n \nramesh@dev-db [11:09:56]> \nYou can also use \\t to display the current time in the hh:mm:ss format as \nshown below: \nramesh@dev-db ~> export PS1=\"\\u@\\h [\\t]> \" \nramesh@dev-db [12:42:55]> \nYou can also use \\@ to display the current time in 12-hour am/pm format \nas shown below: \nramesh@dev-db ~> export PS1=\"[\\@] \\u@\\h> \" \n[04:12 PM] ramesh@dev-db> \nDisplay output of any command in the prompt \nYou can display output of any Linux command in the prompt. The \nfollowing example displays three items separated by | (pipe) in the \ncommand prompt: \n•\n\\!: The history number of the command \n•\n\\h: hostname \n•\n$kernel_version: The output of the uname -r command from \n$kernel_version variable \n•\n\\$?: Status of the last command \nramesh@dev-db ~> kernel_version=$(uname -r) \n100\n"
},
{
"page_number": 101,
"text": "Linux 101 Hacks www.thegeekstuff.com\nramesh@dev-db ~> export PS1=\"\\!|\\h|$kernel_version|\\$?> \" \n473|dev-db|2.6.25-14.fc9.i686|0> \nCreate your own prompt using the available codes for PS1 \nvariable \nUse the following codes and create your own personal PS1 Linux prompt \nthat is functional and suites your taste. \n•\n\\a an ASCII bell character (07) \n•\n\\d the date in “Weekday Month Date” format (e.g., “Tue May 26″) \n•\n\\D{format} - the format is passed to strftime(3) and the result is \ninserted into the prompt string; an empty format results in a \nlocale-specific time representation. The braces are required \n•\n\\e an ASCII escape character (033) \n•\n\\h the hostname up to the first part \n•\n\\H the hostname \n•\n\\j the number of jobs currently managed by the shell \n•\n\\l the basename of the shell’s terminal device name \n•\n\\n newline \n•\n\\r carriage return \n•\n\\s the name of the shell, the basename of $0 (the portion \nfollowing the final slash) \n•\n\\t the current time in 24-hour HH:MM:SS format \n•\n\\T the current time in 12-hour HH:MM:SS format \n•\n\\@ the current time in 12-hour am/pm format \n•\n\\A the current time in 24-hour HH:MM format \n•\n\\u the username of the current user \n•\n\\v the version of bash (e.g., 2.00) \n•\n\\V the release of bash, version + patch level (e.g., 2.00.0) \n101\n"
},
{
"page_number": 102,
"text": "Linux 101 Hacks www.thegeekstuff.com\n•\n\\w the current working directory, with $HOME abbreviated with a \ntilde \n•\n\\W the basename of the current working directory, with $HOME \nabbreviated with a tilde \n•\n\\! the history number of this command \n•\n\\# the command number of this command \n•\n\\$ if the effective UID is 0, a #, otherwise a $ \n•\n\\nnn the character corresponding to the octal number nnn \n•\n\\\\ a backslash \n•\n\\[ begin a sequence of non-printing characters, which could be \nused to embed a terminal control sequence into the prompt \n•\n\\] end a sequence of non-printing character \nUse bash shell function inside PS1 variable \nYou can also invoke a bash shell function in the PS1 as shown below. \nramesh@dev-db ~> function httpdcount { \n> ps aux | grep httpd | grep -v grep | wc -l \n> } \nramesh@dev-db ~> export PS1=\"\\u@\\h [`httpdcount`]> \" \nramesh@dev-db [12]> \n[Note: This displays the total number of running httpd \nprocesses] \nYou can add the following line to your ~/.bash_profile or ~/.bashrc to \nmake this change permanent: \n$ vi .bash_profile \nfunction httpdcount { \n ps aux | grep httpd | grep -v grep | wc -l \n102\n"
},
{
"page_number": 103,
"text": "Linux 101 Hacks www.thegeekstuff.com\n} \nexport PS1='\\u@\\h [`httpdcount`]> ' \nNote: You can also use “pgrep httpd | wc –l” instead of the “ps aux | grep \nhttpd | grep -v grep | wc –l” in the above httpdcount function. \nUse shell script inside PS1 variable \nYou can also invoke a shell script inside the PS1 variable. In the example \nbelow, the ~/bin/totalfilesize.sh, which calculates the total filesize of the \ncurrent directory, is invoked inside the PS1 variable. \nramesh@dev-db ~> cat ~/bin/totalfilesize.sh \nfor filesize in $(ls -l . | grep \"^-\" | awk '{print $5}') \ndo \n let totalsize=$totalsize+$filesize \ndone \necho -n \"$totalsize\" \nramesh@dev-db ~> export PATH=$PATH:~/bin \nramesh@dev-db ~> export PS1=\"\\u@\\h [\\$(totalfilesize.sh) \nbytes]> \" \nramesh@dev-db [534 bytes]> cd /etc/mail \nramesh@dev-db [167997 bytes]> \n[Note: This executes the totalfilesize.sh to display the \ntotal file size of the current directory in the PS1 \nprompt] \nYou can also write the ~/bin/totalfilesize.sh as shown below without the \nfor loop. \n103\n"
},
{
"page_number": 104,
"text": "Linux 101 Hacks www.thegeekstuff.com\nramesh@dev-db ~> cat ~/bin/totalfilesize.sh \nls -l | awk '/^-/ { sum+=$5 } END { printf sum }' \nHack 44. Colorful Bash Prompt Using PS1\nChange foreground color of the prompt \nDisplay prompt in blue color, along with username, host and current \ndirectory information .\nUse the following is for light blue prompt:\n$ export PS1=\"\\e[0;34m\\u@\\h \\w> \\e[m \" \nUse the following for dark blue prompt:\n$ export PS1=\"\\e[1;34m\\u@\\h \\w> \\e[m \" \n•\n\\e[ - Indicates the beginning of color prompt \n•\nx;ym - Indicates color code. Use the color code values mentioned \nbelow. \n•\n\\e[m - indicates the end of color prompt \nColor Code Table: \n•\nBlack 0;30 \n•\nBlue 0;34 \n•\nGreen 0;32 \n•\nCyan 0;36 \n•\nRed 0;31 \n•\nPurple 0;35 \n•\nBrown 0;33 \n104\n"
},
{
"page_number": 105,
"text": "Linux 101 Hacks www.thegeekstuff.com\n[Note: Replace 0 with 1 for dark color] \nMake the color change permanent by adding the following lines your \n~/.bash_profile or ~/.bashrc \n $ vi ~/.bash_profile \nSTARTCOLOR='\\e[0;34m'; \nENDCOLOR=\"\\e[0m\" \nexport PS1=\"$STARTCOLOR\\u@\\h \\w> $ENDCOLOR\" \nChange background color of the prompt \nChange the background color by specifying \\e[{code}m in the PS1 \nprompt as shown below. \nUse the following for Light Gray background:\n$ export PS1=\"\\e[47m\\u@\\h \\w> \\e[m \" \nCombination of background and foreground\nUse the following for Light Blue foreground and Light Gray background\n$ export PS1=\"\\e[0;34m\\e[47m\\u@\\h \\w> \\e[m \" \nAdd the following to your ~/.bash_profile or ~/.bashrc to make the above \nbackground and foreground color permanent. \n$ vi ~/.bash_profile \nSTARTFGCOLOR='\\e[0;34m'; \nSTARTBGCOLOR=\"\\e[47m\" \nENDCOLOR=\"\\e[0m\" \nexport PS1=\"$STARTFGCOLOR$STARTBGCOLOR\\u@\\h \\w> $ENDCOLOR\" \nPlay around by using the following background color and choose the one \nthat match your taste: \n105\n"
},
{
"page_number": 106,
"text": "Linux 101 Hacks www.thegeekstuff.com\n•\n\\e[40m \n•\n\\e[41m \n•\n\\e[42m \n•\n\\e[43m \n•\n\\e[44m \n•\n\\e[45m \n•\n\\e[46m \n•\n\\e[47m \nDisplay multiple colors in the prompt \nYou can also display multiple colors in the same prompt. Add the \nfollowing function to your ~/.bash_profile \nfunction prompt { \n local BLUE=\"\\[\\033[0;34m\\]\" \n local DARK_BLUE=\"\\[\\033[1;34m\\]” \n local RED=”\\[\\033[0;31m\\]” \n local DARK_RED=”\\[\\033[1;31m\\]” \n local NO_COLOR=”\\[\\033[0m\\]” \n case $TERM in \n xterm*|rxvt*) \n TITLEBAR=’\\[\\033]0;\\u@\\h:\\w\\007\\]’ \n ;; \n *) \n TITLEBAR=”\" \n ;; \n esac \n PS1=”\\u@\\h [\\t]> ” \n PS1=”${TITLEBAR}\\ \n $BLUE\\u@\\h $RED[\\t]>$NO_COLOR ” \n PS2=’continue-> ‘ \n PS4=’$0.$LINENO+ ‘ \n106\n"
},
{
"page_number": 107,
"text": "Linux 101 Hacks www.thegeekstuff.com\n} \nYou can re-login for the changes to take effect or source the \n.bash_profile as shown below. \n$. ./.bash_profile \n$ prompt \nramesh@dev-db [13:02:13]> \nChange the prompt color using tput \nYou can also change color of the PS1 prompt using tput as shown below: \n$ export PS1=\"\\[$(tput bold)$(tput setb 4)$(tput setaf \n7)\\]\\u@\\h:\\w $ \\[$(tput sgr0)\\]“ \ntput Color Capabilities: \n•\ntput setab [1-7] - Set a background color using ANSI escape \n•\ntput setb [1-7] - Set a background color \n•\ntput setaf [1-7] - Set a foreground color using ANSI escape \n•\ntput setf [1-7] - Set a foreground color \ntput Text Mode Capabilities: \n•\ntput bold - Set bold mode \n•\ntput dim - turn on half-bright mode \n•\ntput smul - begin underline mode \n•\ntput rmul - exit underline mode \n•\ntput rev - Turn on reverse mode \n•\ntput smso - Enter standout mode (bold on rxvt) \n•\ntput rmso - Exit standout mode \n•\ntput sgr0 - Turn off all attributes \n107\n"
},
{
"page_number": 108,
"text": "Linux 101 Hacks www.thegeekstuff.com\nColor Code for tput: \n•\n0 – Black \n•\n1 – Red \n•\n2 – Green \n•\n3 – Yellow \n•\n4 – Blue \n•\n5 – Magenta \n•\n6 – Cyan \n•\n7 - White \nAny Questions? \nDiscuss it here: Bash Shell PS1: 10 Examples to Make \nYour Linux Prompt like Angelina Jolie\nAdditional tput Examples: \n9 UNIX / Linux tput Examples: Control Your Terminal \nColor and Cursor\n108\n"
},
{
"page_number": 109,
"text": "Linux 101 Hacks www.thegeekstuff.com\nChapter 6: Archive and \nCompression\nHack 45. Zip Command Basics \nHow to zip multiple files? \nsyntax: zip {.zip file-name} {file-names} \n# zip var-log-files.zip /var/log/* \n adding: var/log/acpid (deflated 81%) \n adding: var/log/anaconda.log (deflated 79%) \n adding: var/log/anaconda.syslog (deflated 73%) \n adding: var/log/anaconda.xlog (deflated 82%) \n adding: var/log/audit/ (stored 0%) \n adding: var/log/boot.log (stored 0%) \n adding: var/log/boot.log.1 (deflated 40%) \n adding: var/log/boot.log.2 (deflated 42%) \n adding: var/log/boot.log.3 (deflated 40%) \n adding: var/log/boot.log.4 (deflated 40%) \nHow to zip a directory and it’s files recursively? \n# zip -r var-log-dir.zip /var/log/ \nupdating: var/log/ (stored 0%) \n adding: var/log/wtmp (deflated 78%) \n adding: var/log/scrollkeeper.log (deflated 94%) \n adding: var/log/rpmpkgs.3 (deflated 68%) \n adding: var/log/spooler (stored 0%) \n adding: var/log/cron.2 (deflated 90%) \n109\n"
},
{
"page_number": 110,
"text": "Linux 101 Hacks www.thegeekstuff.com\n adding: var/log/spooler.1 (stored 0%) \n adding: var/log/spooler.4 (stored 0%) \n adding: var/log/httpd/ (stored 0%) \n adding: var/log/rpmpkgs.1 (deflated 68%) \n adding: var/log/anaconda.log (deflated 79%) \n adding: var/log/secure.2 (deflated 93%) \nHow to unzip a *.zip compressed file? \n# unzip var-log.zip \nArchive: var-log.zip \n inflating: var/log/acpid \n inflating: var/log/anaconda.log \n inflating: var/log/anaconda.syslog \n inflating: var/log/anaconda.xlog \n creating: var/log/audit/ \nTo see a detailed output during unzip pass the –v option as shown below. \n# unzip -v var-log.zip \nArchive: var-log.zip \nLength Method Size Ratio Date Time CRC-32 Name \n-------- ------ ------- ----- ---- ---- ------ \n1916 Defl:N 369 81% 02-08-08 14:27 e2ffdc0c \nvar/log/acpid \n13546 Defl:N 2900 79% 02-02-07 14:25 34cc03a1 \nvar/log/anaconda.log \nskip.. \n7680 Defl:N 411 95% 12-30-08 10:55 fe876ee9 \nvar/log/wtmp.1 \n110\n"
},
{
"page_number": 111,
"text": "Linux 101 Hacks www.thegeekstuff.com\n40981 Defl:N 7395 82% 02-08-08 14:28 6386a95e \nvar/log/Xorg.0.log \n-------- ------- --- \n41406991 2809229 93% \n56 files \nHow to list a content of zip file with uncompressing it? \n# unzip -l var-log.zip \nArchive: var-log.zip \n Length Date Time Name \n -------- ---- ---- ---- \n 1916 02-08-08 14:27 var/log/acpid \n 13546 02-02-07 14:25 var/log/anaconda.log \n..skip.. \n 40981 02-08-08 14:28 var/log/Xorg.0.log \n 40981 02-08-07 14:56 var/log/Xorg.0.log.old \n -------- ------- \n 41406991 56 files \nHack 46. Zip Command Advanced \nCompression\nThere are 10 levels of compression provided by zip command. \n•\nLevel 0 is the lowest level, where it just archives the file without \nany compression. \n•\nLevel 1 will perform little compression. But, will be very fast. \n•\nLevel 6 is the default level of compression. \n111\n"
},
{
"page_number": 112,
"text": "Linux 101 Hacks www.thegeekstuff.com\n•\nLevel 9 is the maximum compression. This will be slower when \ncompared to default level. In my opinion, unless you are \ncompressing a huge file, you should always use level 9. \nIn the example below, I used Level 0, default Level 6, and Level 9 \ncompression on a same directory. See the compressed file size yourself. \n# zip var-log-files-default.zip /var/log/* \n# zip -0 var-log-files-0.zip /var/log/* \n# zip -9 var-log-files-9.zip /var/log/* \n# ls -ltr \n-rw-r--r-- 1 root root 2817248 Jan 1 13:05 \nvar-log-files-default.zip \n-rw-r--r-- 1 root root 41415301 Jan 1 13:05 \nvar-log-files-0.zip \n-rw-r--r-- 1 root root 2582610 Jan 1 13:06 \nvar-log-files-9.zip \nValidate a zip archive \nSometime you may want to validate a zip archive without extracting it. \nTo test the validity of the zip file, pass option –t as shown below. \n# unzip -t var-log.zip \n Archive: var-log.zip \n testing: var/log/acpid OK \n testing: var/log/anaconda.log OK \n testing: var/log/anaconda.syslog OK \nskip... \n testing: var/log/wtmp OK \n112\n"
},
{
"page_number": 113,
"text": "Linux 101 Hacks www.thegeekstuff.com\n testing: var/log/wtmp.1 OK \n testing: var/log/Xorg.0.log OK \nNo errors detected in compressed data of var-log.zip. \nHack 47. Password Protection of Zip files \nPass the option –P to the zip command to assign a password to the zip \nfile. \n# zip -P mysecurepwd var-log-protected.zip /var/log/* \nThe above option is good if you are using the command inside a shell-\nscript for background jobs. However, when you are performing the \ncompression interactively on the command-line, you don’t want the \npassword to be visible in the history. So, use the option –e as shown \nbelow to assign the password. \n# zip -e var-log-protected.zip /var/log/* \nEnter password: \nVerify password: \nupdating: var/log/acpid (deflated 81%) \nupdating: var/log/anaconda.log (deflated 79%) \nWhen you are uncompressing a password protected file, it will ask for \nthe password as shown below. \n# unzip var-log-protected.zip \nArchive: var-log-protected.zip \n[var-log-protected.zip] var/log/acpid password: \nHack 48. Tar Command Examples \ntar command (tape archive) is used to convert a group of files into an \narchive. \n113\n"
},
{
"page_number": 114,
"text": "Linux 101 Hacks www.thegeekstuff.com\nSyntax: \ntar [options] [tar-archive-name] [other-file-names] \nHow can I create a single backup file of all files and \nsubdirectories under my home directory? \nThe following command creates a single archive backup file called \nmy_home_directory.tar under /tmp. This archive will contain all the files \nand subdirectories under /home/jsmith. \n•\nOption c, stands for create an archive. \n•\nOption v stands for verbose mode, displays additional \ninformation while executing the command. \n•\nOption f indicates the archive file name mentioned in the \ncommand. \n# tar cvf /tmp/my_home_directory.tar /home/jsmith \nHow do I view all the files inside the tar archive? \nOption t will display all the files from the tar archive. \n# tar tvf /tmp/my_home_directory.tar \nHow do I extract all the files from a tar archive? \nOption x will extract the files from the tar archive as shown below. This \nwill extract the content to the current directory location from where the \ncommand is executed. \n# tar xvf /tmp/my_home_directory.tar \nHow do I extract tar.gz files to a specific directory? \n# tar xvfz /tmp/my_home_directory.tar.gz –C /home/ramesh \n114\n"
},
{
"page_number": 115,
"text": "Linux 101 Hacks www.thegeekstuff.com\nAdditional Tar Examples:\nThe Ultimate Tar Command Tutorial with 10 Practical \nExamples\nHack 49. Combine gzip, bzip2 with Tar \nHow to use gzip with tar? \nAdd option z to the tar command when dealing with tar.gz compressed \nfile. \n# tar cvfz /tmp/my_home_directory.tar.gz /home/jsmith \n# tar xvfz /tmp/my_home_directory.tar.gz \n# tar tvfz /tmp/my_home_directory.tar.gz \nNote: Using gzip is faster when compared to bzip2. \nHow to use bzip2 with tar? \nAdd option j to the tar command when dealing with tar.bz2 compressed \nfile. \n# tar cvfj /tmp/my_home_directory.tar.bz2 /home/jsmith \n# tar xvfj /tmp/my_home_directory.tar.bz2 \n# tar tvfj /tmp/my_home_directory.tar.bz2 \nNote: Using bizp2 gives higher level of compression when compared to \ngzip.\n115\n"
},
{
"page_number": 116,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 50. BZ is Eazy! Bz* Command Examples\nbzip2 command is used for compression and decompression of files. The \nmain advantage of bzip2 is the best compression size. \nbzip2 vs gzip: \n•\nbzip2 will compress better than gzip. \n•\nSpeed of bzip2 is somewhat slower than gzip and zip. \n•\nbzip2 provides high rate of compression with reasonable speed. \nThere are several Linux bz commands available to manipulate the bzip2 \nfiles. This hack explains various bz commands with 6 practical examples. \nCompressing a file using bzip2 \nWhen you compress a file using bzip2 command, it creates a \ncompressed file with *.bz2 extension as shown below. \n$ bzip2 trace \n$ ls -l trace.bz2 \n-rw-r--r-- 1 root root 54167 Jan 23 2009 trace.bz2 \nSearch operation in bzip2 file using bzgrep \nbzgrep command is used to search for a string or a pattern (regular \nexpression) on bzip2 compressed files. \nbzgrep will apply grep to data from files in the bzip2 format without \nrequiring on-disk decompression. So all the options of a grep command \nwill be applied for bzgrep also. \nSyntax: \nbzgrep grep-options -e pattern filename \n116\n"
},
{
"page_number": 117,
"text": "Linux 101 Hacks www.thegeekstuff.com\nIn the below example, trace.bz2 is a compressed trace file which is of \nsize 58M. \n$ bzgrep -i \"CONSOLE=.*\" trace.bz2 \n2010-10-11T08:40:28.100 gs(16985): CONSOLE=/dev/pts/0 \n2010-10-11T08:40:29.772 gs(17031): CONSOLE=/dev/pts/0 \n2010-10-11T08:40:58.140 gs(17099): CONSOLE=/dev/pts/0 \n2010-10-11T08:41:27.547 gs(17164): CONSOLE=/dev/pts/0 \n2010-10-11T08:41:57.962 gs(17233): CONSOLE=/dev/pts/0 \n2010-10-11T08:42:28.392 gs(17294): CONSOLE=/dev/pts/0 \n2010-10-11T08:42:57.721 gs(17439): CONSOLE=/dev/pts/0 \nIf bzgrep is not there, you have to decompress the file manually and do \na grep on that, where bzgrep does this process internally and gives you \nthe required output. bzegrep and bzfgrep commands will apply egrep \nand fgrep operation on bzip2 files respectively. \nView the bzip2 file using bzcat \nIf you want only to read the compressed file without decompressing it, \nuse the bzcat command as shown below. \n$ bzcat trace.bz2 \n0: ERR: Wed Sep 22 09:59:42 2010: \ngs(11153/47752677794640): [chk_sqlcode.scp:92]: Database: \nORA-01653: unable to extend table OPC_OP.OP \nC_HIST_MESSAGES (OpC50-15) \n0: ERR: Wed Sep 22 09:59:47 2010: \ngs(11153/47752677794640): [chk_sqlcode.scp:92]: Database: \nORA-01653: unable to extend table OPC_OP.OP \nC_HIST_MESSAGES (OpC50-15) \nRetry. (OpC51-22) \nDatabase: ORA-01653: unable to extend table \nOPC_OP.OPC_HIST_MESSAGES by 64 in tablespace OPC_6 \n(OpC50-15) \n. \n117\n"
},
{
"page_number": 118,
"text": "Linux 101 Hacks www.thegeekstuff.com\n. \nbzcat command displays the uncompressed content into standard \noutput file for the users to view the content. \nPaging bzip2 compressed file with bzless & bzmore \nbzless and bzmore command allows you to view the content of bzip2 \ncompressed files page by page. bzmore works on files compressed with \nbzip2 and also on uncompressed files. \n$ bzless trace.bz2 \n$ bzmore trace.bz2 \n0: ERR: Wed Sep 22 09:59:42 2010: \ngs(11153/47752677794640): [chk_sqlcode.scp:92]: Database: \nORA-01653: unable to extend table OPC_OP.OP \nC_HIST_MESSAGES (OpC50-15) \n0: ERR: Wed Sep 22 09:59:47 2010: \ngs(11153/47752677794640): [chk_sqlcode.scp:92]: Database: \nORA-01653: unable to extend table OPC_OP.OP \nC_HIST_MESSAGES (OpC50-15) \nRetry. (OpC51-22) \nDatabase: ORA-01653: unable to extend table \nOPC_OP.OPC_HIST_MESSAGES by 64 in tablespace OPC_6 \n(OpC50-15) \n. \n. \n--More-- \nCompare bzip2 files using bzcmp \nYou can compare two bzip2 compressed file using bzcmp command. It \ninternally uses cmp command to compare the content of the \ncompressed contents. Here you can see the output of comparison of the \ntwo normal files and compressed files. \n118\n"
},
{
"page_number": 119,
"text": "Linux 101 Hacks www.thegeekstuff.com\n$ cmp System.txt.001 System.txt.002 \nSystem.txt.001 System.txt.002 differ: byte 20, line 2 \n \n$ bzcmp System.txt.001.bz2 System.txt.002.bz2 \n- /tmp/bzdiff.csgqG32029 differ: byte 20, line 2 \nFind the difference between two bzip2 files using bzdiff \nIn Linux, diff command will compare two files and give you the lowdown \non just how different they are. If you give bz2 files to diff command, it \nwill not be in a position to explain the difference. \nFor bzip2 compressed files, bzdiff command gives the differences of two \nbzip2 compressed files as shown below. \n$ bzdiff System.txt.001.bz2 System.txt.002.bz2 \n2c2 \n< 0: ERR: Mon Sep 27 12:19:34 2010: gs(11153/1105824064): \n[chk_sqlcode.scp:92]: Database: ORA-01654: unable to \nextend index OPC_OP.OPCX \n_ANNO_NUM by 64 in tablespace OPC_INDEX1 \n--- \n> 0: ERR: Wed Sep 22 09:59:42 2010: \ngs(11153/47752677794640): [chk_sqlcode.scp:92]: Database: \nORA-01653: unable to extend table OPC_OP. \nOPC_HIST_MESSAGES by 64 in tablespace OPC_6 \n4,5c4 \n< Retry. (OpC51-22) \n< Database: ORA-01654: unable to extend index \nOPC_OP.OPCX_ANNO_NUM by 64 in tablespace OPC_INDEX1 \n--- \n> 0: ERR: Wed Sep 22 09:59:47 2010: \ngs(11153/47752677794640): [chk_sqlcode.scp:92]: Database: \nORA-01653: unable to extend table OPC_OP. \nOPC_HIST_MESSAGES by 64 in tablespace OPC_6\n119\n"
},
{
"page_number": 120,
"text": "Linux 101 Hacks www.thegeekstuff.com\nAny Questions?\nDiscuss it here: bzip2, bzgrep, bzcmp, bzdiff, bzcat, \nbzless, bzmore examples\nHack 51. Cpio Examples \ncpio command is used to process archive files (for example, *.cpio or \n*.tar files). \ncpio stands for “copy in, copy out”. \ncpio performs the following three operations. \n1.\nCopying files to an archive \n2.\nExtracting files from an archive \n3.\nPassing files to another directory tree \ncpio takes the list of files from the standard input while creating an \narchive, and sends the output to the standard output. \nCreate *.cpio Archive File \nYou can create a *.cpio archive that contains files and directories using \ncpio -ov \n$ cd objects \n$ ls \nfile1.o file2.o file3.o \n$ ls | cpio -ov > /tmp/object.cpio \n120\n"
},
{
"page_number": 121,
"text": "Linux 101 Hacks www.thegeekstuff.com\nAs seen above, the ls command passes the three object filenames to \ncpio command and cpio generates the object.cpio archive. \nExtract *.cpio Archive File \ncpio extract: To extract a given *.cpio file, use cpio -iv as shown below. \n$ mkdir output \n$ cd output \n$ cpio -idv < /tmp/object.cpio \nCreate *.cpio Archive with Selected Files \nThe following example creates a *.cpio archive only with *.c files. \n$ find . -iname *.c -print | cpio -ov >/tmp/c_files.cpio \nCreate *.tar Archive File using cpio -F \nWe already know how to use the tar command effectively. \nDid you know that you can also use cpio command to create tar files as \nshown below? \n$ ls | cpio -ov -H tar -F sample.tar \nAs seen above, instead of redirecting the standard output you can \nmention the output archive filename with the option -F.\nExtract *.tar Archive File using cpio command \nYou can also extract a tar file using cpio command as shown below. \n$ cpio -idv -F sample.tar \n121\n"
},
{
"page_number": 122,
"text": "Linux 101 Hacks www.thegeekstuff.com\nView the content of *.tar Archive File \nTo view the content of *.tar file, do the following. \n$ cpio -it -F sample.tar \nCreate a *.cpio Archive with the Original files that a \nSymbolic Link Points \ncpio archive can be created with the original files that a symbolic link is \nreferring to as shown below. \n$ ls | cpio -oLv >/tmp/test.cpio \nPreserve the File Modification Time while restoring *.cpio \nThe modification time of the files can be preserved when we are \nrestoring the cpio archive files as shown below. \n$ ls | cpio -omv >/tmp/test.cpio \nCopy Directory Tree from One to Another \ncpio allows you to copy one directory contents into another directory \nwithout creating an intermediate archive. It reads the file list from the \nstandard input and pass it to the target directory. \nThe example below copies the files and sub-directories of objects \ndirectory into /mnt/out directory. \n$ mkdir /mnt/out \n$ cd objects \n$ find . -depth | cpio -pmdv /mnt/out \nIn the above example: \n122\n"
},
{
"page_number": 123,
"text": "Linux 101 Hacks www.thegeekstuff.com\n•\ncpio option -p makes cpio to use pass through mode. Its like \npiping cpio -o into cpio -i. \n•\ncpio option -d creates leading directories as needed in the target \ndirectory.\nAny Questions?\nDiscuss it here: Linux cpio Examples: How to Create and \nExtract cpio Archives (and tar archives)\nAdditional cpio Examples:\nHow to View, Modify and Recreate initrd.img Using cpio \nCommand\n123\n"
},
{
"page_number": 124,
"text": "Linux 101 Hacks www.thegeekstuff.com\nChapter 7: Command Line History \nHack 52. Bash Command Line History \nExamples\nWhen you are using Linux command line frequently, using the history \neffectively can be a major productivity boost. In fact, once you have \nmastered the 15 examples that I’ve provided here, you’ll find using \ncommand line more enjoyable and fun. \nSearch the history using Control+R \nI strongly believe that this may be your most frequently used feature of \nhistory. When you’ve already executed a very long command, you can \nsimply search history using a keyword and re-execute the same \ncommand without having to type it fully. Press Control+R and type the \nkeyword. \nIn the following example, I searched for red, which displayed the \nprevious command “cat /etc/redhat-release” in the history that \ncontained the word red. \n# [Note: Press Ctrl+R from the command prompt, which will \ndisplay the reverse-i-search prompt as shown below] \n(reverse-i-search)`red‘: cat /etc/redhat-release \n[Note: Press enter when you see your command, which will \nexecute the command from the history] \n# cat /etc/redhat-release \nFedora release 9 (Sulphur) \nSometimes you want to edit a command from history before executing \nit. For e.g. you can search for httpd, which will display service httpd stop \nfrom the command history, select this command and change the stop to \nstart and re-execute it again as shown below. \n124\n"
},
{
"page_number": 125,
"text": "Linux 101 Hacks www.thegeekstuff.com\n # [Note: Press Ctrl+R from the command prompt, which will \ndisplay the reverse-i-search prompt] \n(reverse-i-search)`httpd‘: service httpd stop \n[Note: Press either left arrow or right arrow key when you \nsee your command, which will display the command for you \nto edit, before executing it] \n# service httpd start \nRepeat previous command quickly using 4 different \nmethods \nSometime you may end up repeating the previous commands for various \nreasons. Following are the 4 different ways to repeat the last executed \ncommand. \n1.\nUse the up arrow to view the previous command and press enter \nto execute it. \n2.\nType !! and press enter from the command line \n3.\nType !-1 and press enter from the command line. \n4.\nPress Control+P will display the previous command, press enter \nto execute it \nExecute a specific command from history \nIn the following example, If you want to repeat the command #4, \nexecute !4 as shown below. \n# history | more \n 1 service network restart \n 2 exit \n 3 id \n 4 cat /etc/redhat-release \n# !4 \ncat /etc/redhat-release \n125\n"
},
{
"page_number": 126,
"text": "Linux 101 Hacks www.thegeekstuff.com\nFedora release 9 (Sulphur) \nExecute previous command that starts with a specific \nword \nType ! followed by the starting few letters of the command that you \nwould like to re-execute. In the following example, typing !ps and enter, \nexecuted the previous command starting with ps, which is ‘ps aux | grep \nyp’. \n# !ps \nps aux | grep yp \nroot 16947 0.0 0.1 36516 1264 ? Sl 13:10 0:00 ypbind \nClear all the previous history using option -c \nSometime you may want to clear all the previous history. However you \nmay still want to keep the history moving forward. \n# history -c \nSubstitute words from history commands \nWhen you are searching through history, you may want to execute a \ndifferent command but use the same parameter from the command that \nyou’ve just searched. \nIn the example below, the !!:$ next to the vi command gets the \nargument from the previous command to the current command. \n# ls anaconda-ks.cfg \nanaconda-ks.cfg \n# vi !!:$ \nvi anaconda-ks.cfg \n126\n"
},
{
"page_number": 127,
"text": "Linux 101 Hacks www.thegeekstuff.com\nIn the example below, the !^ next to the vi command gets the first \nargument from the previous command (i.e cp command) to the current \ncommand (i.e vi command). \n# cp anaconda-ks.cfg anaconda-ks.cfg.bak \nanaconda-ks.cfg \n# vi !^ \nvi anaconda-ks.cfg \nSubstitute a specific argument for a specific command \nIn the example below, !cp:2 searches for the previous command in \nhistory that starts with cp and takes the second argument of cp and \nsubstitutes it for the ls -l command as shown below. \n# cp ~/longname.txt /really/a/very/long/path/long-\nfilename.txt \n# ls -l !cp:2 \nls -l /really/a/very/long/path/long-filename.txt \nIn the example below, !cp:$ searches for the previous command in \nhistory that starts with cp and takes the last argument (in this case, \nwhich is also the second argument as shown above) of cp and \nsubstitutes it for the ls -l command as shown below. \n# ls -l !cp:$ \nls -l /really/a/very/long/path/long-filename.txt \n127\n"
},
{
"page_number": 128,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 53. History Related Environment \nVariables\nDisplay TIMESTAMP in history using HISTTIMEFORMAT \nTypically when you type history from command line, it displays the \ncommand# and the command. For auditing purpose, it may be \nbeneficial to display the timestamp along with the command as shown \nbelow. \n# export HISTTIMEFORMAT=’%F %T ‘ \n \n# history | more \n 1 2008-08-05 19:02:39 service network restart \n 2 2008-08-05 19:02:39 exit \n 3 2008-08-05 19:02:39 id \n 4 2008-08-05 19:02:39 cat /etc/redhat-release \nNote: You can also setup the following alias to view the recent history \ncommands. \nalias h1='history 10' \nalias h2='history 20' \nalias h3='history 30' \nControl the total number of lines in the history using \nHISTSIZE \nAppend the following two lines to the .bash_profile and relogin to the \nbash shell again to see the change. In this example, only 450 command \nwill be stored in the bash history. \n# vi ~/.bash_profile \nHISTSIZE=450 \nHISTFILESIZE=450 \n128\n"
},
{
"page_number": 129,
"text": "Linux 101 Hacks www.thegeekstuff.com\nChange the history file name using HISTFILE \nBy default, history is stored in ~/.bash_history file. Add the following line \nto the .bash_profile and relogin to the bash shell, to store the history \ncommand in .commandline_warrior file instead of .bash_history file. I’m \nyet to figure out a practical use for this. I can see this getting used when \nyou want to track commands executed from different terminals using \ndifferent history file name. \n# vi ~/.bash_profile \nHISTFILE=/root/.commandline_warrior \nEliminate the continuous repeated entry from history \nusing HISTCONTROL \nIn the following example pwd was typed three times, when you do \nhistory, you can see all the 3 continuous occurrences of it. To eliminate \nduplicates, set HISTCONTROL to ignoredups as shown below. \n# pwd \n# pwd \n# pwd \n# history | tail -4 \n 44 pwd \n 45 pwd \n 46 pwd \n 47 history | tail -4 \n[Note: There are three pwd commands in history, after \nexecuting pwd 3 times as shown above] \n# export HISTCONTROL=ignoredups \n# pwd \n129\n"
},
{
"page_number": 130,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# pwd \n# pwd \n \n# history | tail -3 \n 56 export HISTCONTROL=ignoredups \n 57 pwd \n 58 history | tail -4 \n[Note: There is only one pwd command in the history, even \nafter executing pwd 3 times as shown above] \nErase duplicates across the whole history using \nHISTCONTROL \nThe ignoredups shown above removes duplicates only if they are \nconsecutive commands. To eliminate duplicates across the whole \nhistory, set the HISTCONTROL to erasedups as shown below. \n# export HISTCONTROL=erasedups \n# pwd \n# service httpd stop \n# history | tail -3 \n 38 pwd \n 39 service httpd stop \n 40 history | tail -3 \n# ls -ltr \n# service httpd stop \n130\n"
},
{
"page_number": 131,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# history | tail -6 \n 35 export HISTCONTROL=erasedups \n 36 pwd \n 37 history | tail -3 \n 38 ls –ltr \n 39 service httpd stop \n 40 history | tail -6 \n[Note: The previous service httpd stop after pwd got \nerased] \nForce history not to remember a particular command \nusing HISTCONTROL \nWhen you execute a command, you can instruct history to ignore the \ncommand by setting HISTCONTROL to ignorespace AND typing a space \nin front of the command as shown below. I can see lot of junior \nsysadmins getting excited about this, as they can hide a command from \nthe history. \nIt is good to understand how ignorespace works. But, as a best practice, \ndon’t hide purposefully anything from history. \n# export HISTCONTROL=ignorespace \n# ls –ltr \n# pwd \n# service httpd stop \n[Note: There is a space at the beginning of service, to \nignore this command from history] \n# history | tail -3 \n131\n"
},
{
"page_number": 132,
"text": "Linux 101 Hacks www.thegeekstuff.com\n 67 ls –ltr \n 68 pwd \n 69 history | tail -3 \nDisable the usage of history using HISTSIZE \nIf you want to disable history all together and don’t want bash shell to \nremember the commands you’ve typed, set the HISTSIZE to 0 as shown \nbelow. \n# export HISTSIZE=0 \n# history \n# [Note: History did not display anything] \nIgnore specific commands from the history using \nHISTIGNORE \nSometimes you may not want to clutter your history with basic \ncommands such as pwd and ls. Use HISTIGNORE to specify all the \ncommands that you want to ignore from the history. \nPlease note that adding ls to the HISTIGNORE ignores only ls and not ls \n-l. So, you have to provide the exact command that you would like to \nignore from the history. \n# export HISTIGNORE=”pwd:ls:ls –ltr:” \n# pwd \n# ls \n# ls -ltr \n# service httpd stop \n# history | tail -3 \n 79 export HISTIGNORE=”pwd:ls:ls -ltr:” \n 80 service httpd stop \n132\n"
},
{
"page_number": 133,
"text": "Linux 101 Hacks www.thegeekstuff.com\n 81 history \n[Note: History did not display pwd and ls]\nAny Questions?\nDiscuss it here: 15 Examples To Master Linux Command \nLine History\nHack 54. History Expansion Examples \nUsing history expansion you can pick a specific command from the \nhistory, execute it as it is, or modify it and execute it based on your \nneeds. The ! starts the history expansion. \n•\n!! Repeats the previous command \n•\n!10 Repeat the 10th command from the history \n•\n!-2 Repeat the 2nd command (from the last) from the history \n•\n!string Repeat the command that starts with “string” from the \nhistory \n•\n!?string Repeat the command that contains the word “string” \nfrom the history \n•\n^str1^str2^ Substitute str1 in the previous command with str2 \nand execute it \n•\n!!:$ Gets the last argument from the previous command. \n•\n!string:n Gets the nth argument from the command that starts \nwith “string” from the history. \n!?string Example \nLet us assume that you've executed the following command at some \npoint and it is somewhere in the history. \n$ /usr/local/apache2/bin/apachectl restart \n133\n"
},
{
"page_number": 134,
"text": "Linux 101 Hacks www.thegeekstuff.com\nLater when you want to execute the same command, if you try the \nfollowing it will fail because it is looking for a line that starts with \n“apache”. \n$ !apache \n-bash: !apache: event not found \nHowever if you do the following, it will look for any command that \ncontains the string “apache” and execute it as shown below. \n$ !?apache \n/usr/local/apache2/bin/apachectl restart \n^str1^str2^ Example \nSometimes you might check whether a file exists using a quick ls \ncommand as shown below. \n$ ls /etc/sysconfig/network \nOnce you verify that the file exists, to view the content of the file using \nvi, you don't need to type the whole file name again. Instead do the \nfollowing, which will replace the word 'ls' in the previous command with \nthe word 'vi' and execute the command. \n$ ^ls^vi \nvi /etc/sysconfig/network \n!!:$ Example \nIn this example, the following command takes a copy of the /etc/passwd \nfile to the home directory as passwd.bak. \n$ cp /etc/passwd /home/ramesh/passwd.bak \nOnce you create the backup of the file, if you want to open the backup \nfile, you don't need to type the whole backup file name again. Instead, \n134\n"
},
{
"page_number": 135,
"text": "Linux 101 Hacks www.thegeekstuff.com\nyou can use the last argument of the previous command along with 'vi' \ncommand as shown below. \n$ vi !!:$ \nvi /home/ramesh/passwd.bak \nPlease note that “!:$” is exactly same as “!!:$”. So, the above example \ncan also be executed as shown below. \n$ vi !:$ \nvi /home/ramesh/passwd.bak \n!string:n Example \nWhen you execute a command that has multiple arguments (as shown in \nthe tar command example below), you can extract only a specific \nargument from it for later use. \n$ tar cvfz ~/sysconfig.tar.gz /etc/sysconfig/* \nNow if you want to ls the newly created tar.gz file, you can do the \nfollowing, which will take the 2nd argument of the previous tar \ncommand. \n$ ls -l !tar:2 \nls -l ~/sysconfig.tar \nAdditional Bash History Expansion Examples:\n15 Linux Bash History Expansion Examples You Should Know\n135\n"
},
{
"page_number": 136,
"text": "Linux 101 Hacks www.thegeekstuff.com\nChapter 8: System Administration \nTasks\nHack 55. Partition Using fdisk\nAfter you’ve installed brand new disks on your server, you have to use \ntools like fdisk to partition it accordingly. \nFollowing are the 5 typical actions (commands) that you can execute \ninside fdisk. \n•\nn – New Partition creation \n•\nd – Delete an existing partition \n•\np - Print Partition Table \n•\nw – Write the changes to the partition table. i.e save. \n•\nq – Quit the fdisk utility \nCreate a partition \nIn the following example, I created a /dev/sda1 primary partition. \n# fdisk /dev/sda \nCommand (m for help): p \nDisk /dev/sda: 287.0 GB, 287005343744 bytes \n255 heads, 63 sectors/track, 34893 cylinders \nUnits = cylinders of 16065 * 512 = 8225280 bytes \nDevice Boot Start End Blocks Id System \nCommand (m for help): n \nCommand action \n e extended \n136\n"
},
{
"page_number": 137,
"text": "Linux 101 Hacks www.thegeekstuff.com\n p primary partition (1-4) \np \nPartition number (1-4): 1 \nFirst cylinder (1-34893, default 1): \nUsing default value 1 \nLast cylinder or +size or +sizeM or +sizeK (1-34893, \ndefault 34893): \nUsing default value 34893 \nCommand (m for help): w \nThe partition table has been altered! \nCalling ioctl() to re-read partition table. \nSyncing disks. \nVerify that the partition got created successfully \n# fdisk /dev/sda \nCommand (m for help): p \nDisk /dev/sda: 287.0 GB, 287005343744 bytes \n255 heads, 63 sectors/track, 34893 cylinders \nUnits = cylinders of 16065 * 512 = 8225280 bytes \nDevice Boot Start End Blocks Id System \n/dev/sda1 1 34893 280277991 83 Linux \nCommand (m for help): q \n137\n"
},
{
"page_number": 138,
"text": "Linux 101 Hacks www.thegeekstuff.com\nAdditional fdisk Examples:\n7 Linux fdisk Command Examples to Manage Hard Disk \nPartition\nHack 56. Format a Partition Using mke2fsk \nAfter partitioning the disks, it is still not ready for usage, as we need to \nformat the disk. At this stage, if you try to view the disk information, it \nwill give the following error message indicating that no valid superblock \nis present. \n# tune2fs -l /dev/sda1 \ntune2fs 1.35 (28-Feb-2004) \ntune2fs: Bad magic number in super-block while trying to \nopen /dev/sda1 \nCouldn't find valid filesystem superblock. \nTo format the disk, use mke2fs as shown below. \n# mke2fs /dev/sda1 \nYou can also pass the following optional parameter to the mke2fs. \n•\n-m 0 : reserved-blocks-percentage – This indicates the \npercentage of the filesystem blocks reserved for the root user. \nDefault is 5%. In the following example, it is set to 0. \n•\n-b 4096 : block-size specified in bytes. Valid values are 1024, \n2048 and 4096 bytes per block. \n# mke2fs -m 0 -b 4096 /dev/sda1 \nmke2fs 1.35 (28-Feb-2004) \n138\n"
},
{
"page_number": 139,
"text": "Linux 101 Hacks www.thegeekstuff.com\nFilesystem label= \nOS type: Linux \nBlock size=4096 (log=2) \nFragment size=4096 (log=2) \n205344 inodes, 70069497 blocks \n0 blocks (0.00%) reserved for the super user \nFirst data block=0 \nMaximum filesystem blocks=71303168 \n2139 block groups \n32768 blocks per group, 32768 fragments per group \n96 inodes per group \nSuperblock backups stored on blocks: \n32768, 98304, 163840, 229376, 294912, 819200, 884736, \n1605632, 2654208, 4096000, 7962624, 11239424, 20480000, \n23887872 \nWriting inode tables: done \nWriting superblocks and filesystem accounting information: \ndone \nThis filesystem will be automatically checked every 32 \nmounts or 180 days, whichever comes first. Use tune2fs -c \nor -i to override. \nThe above command will create an ext2 filesystem. To create an ext3 file \nsystem do the following: \n# mkfs.ext3 /dev/sda1 \n# mke2fs –j /dev/sda1 \n139\n"
},
{
"page_number": 140,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 57. Mount a Partition \nAfter creating a partition and formatting, you can mount it to a mount \npoint. \nFirst create a directory where the partition should be mounted. \n# mkdir /home/database \nMount the file system. \n# mount /dev/sda1 /home/database \n \nTo automatically mount the filesystem after the reboot, add the following \nentry to the /etc/fstab \n/dev/sda1 /home/database ext3 defaults 0 2 \nHack 58. Fine Tune a Partition Using tune2fs \nUse the tune2fs –l /dev/sda1 to view the filesystem information as shown \nbelow. \n# tune2fs -l /dev/sda1 \ntune2fs 1.35 (28-Feb-2004) \nFilesystem volume name: /home/database \nLast mounted on: \nFilesystem UUID: f1234556-e123-1234-abcd-\nbbbbaaaaae11 \nFilesystem magic number: 0xEF44 \nFilesystem revision #: 1 (dynamic) \nFilesystem features: resize_inode filetype \nsparse_super \nDefault mount options: (none) \nFilesystem state: not clean \n140\n"
},
{
"page_number": 141,
"text": "Linux 101 Hacks www.thegeekstuff.com\nErrors behavior: Continue \nFilesystem OS type: Linux \nInode count: 1094912 \nBlock count: 140138994 \nReserved block count: 0 \nFree blocks: 16848481 \nFree inodes: 1014969 \nFirst block: 0 \nBlock size: 2048 \nFragment size: 2048 \nReserved GDT blocks: 512 \nBlocks per group: 16384 \nFragments per group: 16384 \nInodes per group: 128 \nInode blocks per group: 8 \nFilesystem created: Tue Jul 1 00:06:03 2008 \nLast mount time: Thu Aug 21 05:58:25 2008 \nLast write time: Fri Jan 2 15:40:36 2009 \nMount count: 2 \nMaximum mount count: 20 \nLast checked: Tue Jul 1 00:06:03 2008 \nCheck interval: 15552000 (6 months) \nNext check after: Sat Dec 27 23:06:03 2008 \nReserved blocks uid: 0 (user root) \nReserved blocks gid: 0 (group root) \nFirst inode: 11 \nInode size: 128 \nDefault directory hash: tea \nDirectory Hash Seed: 12345829-1236-4123-9aaa-\nccccc123292b \n141\n"
},
{
"page_number": 142,
"text": "Linux 101 Hacks www.thegeekstuff.com\nYou can also use the tune2fs to tune the ex2/ext3 filesystem parameter. \nFor example, if you want to change the Filesystem volume name, you \ncan do it as shown below. \n# tune2fs -l /dev/sda1 | grep volume \nFilesystem volume name: /home/database \n# tune2fs -L database-home /dev/emcpowera1 \ntune2fs 1.35 (28-Feb-2004) \n# tune2fs -l /dev/sda1 | grep volume \nFilesystem volume name: database-home \nHack 59. Create a Swap File System\nCreate a file for swap usage as shown below. \n# dd if=/dev/zero of=/home/swap-fs bs=1M count=512 \n512+0 records in \n512+0 records out \n# ls -l /home/swap-fs \n-rw-r--r-- 1 root root 536870912 Jan 2 23:13 /home/swap-\nfs \nUse mkswap to setup a Linux swap area in the /home/swap-fs file that \nwas created above. \n# mkswap /home/swap-fs \nSetting up swapspace version 1, size = 536866 kB \nOnce the file is created and has been setup for Linux swap area, it is \ntime to enable the swap using swapon as shown below. \n142\n"
},
{
"page_number": 143,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# swapon /home/swap-fs \nAdd the following line to /etc/fstab and reboot the system for the swap \nto take into effect. \n/home/swap-fs swap swap defaults 0 0 \nAdditional Swap Examples:\n2 Ways to Add Swap Space Using dd, mkswap and swapon\nHack 60. Create a New User\nAdd a new user – Basic method \nSpecify only the user name. \n# useradd jsmith \nAdd a new user with additional Parameter \nYou can also specify the following parameter to the useradd \n•\n-c : Description about the user. \n•\n-e : expiry date of the user in mm/dd/yy format \n# adduser -c \"John Smith - Oracle Developer\" -e 12/31/09 \njsmith \nVerify that the user got added successfully. \n# grep jsmith /etc/passwd \njsmith:x:510:510:John Smith - Oracle \nDeveloper:/home/jsmith:/bin/bash \n143\n"
},
{
"page_number": 144,
"text": "Linux 101 Hacks www.thegeekstuff.com\nChange the user password\n# passwd jsmith \nChanging password for user jsmith. \nNew UNIX password: \nBAD PASSWORD: it is based on a dictionary word \nRetype new UNIX password: \npasswd: all authentication tokens updated successfully. \nHow to identify the default values used by useradd? \nFollowing are the default values that will be used when an user is \ncreated. \n# useradd –D \nGROUP=100 \nHOME=/home \nINACTIVE=-1 \nEXPIRE= \nSHELL=/bin/bash \nSKEL=/etc/skel \nAdditional User Creation Examples: \nThe Ultimate Guide to Create Users in Linux / Unix\nThe Ultimate Guide for Creating Strong Passwords\n144\n"
},
{
"page_number": 145,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 61. Create a New Group \nCreate a new developer group\n# groupadd developers \nValidate that the group was created successfully. \n# grep developer /etc/group \ndevelopers:x:511: \nAdd an user to an existing group\nYou cannot use useradd to modify an existing user, as you’ll get the \nfollowing error message. \n# useradd -G developers jsmith \nuseradd: user jsmith exists \n \n# usermod -g developers jsmith \nValidate the users group was modified successfully\n# grep jsmith /etc/passwd \njsmith:x:510:511:Oracle Developer:/home/jsmith:/bin/bash \n# id jsmith \nuid=510(jsmith) gid=511(developers) groups=511(developers) \n# grep jsmith /etc/group \njsmith:x:510: \ndevelopers:x:511:jsmith \n145\n"
},
{
"page_number": 146,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 62. Setup SSH Passwordless Login in \nOpenSSH \nYou can login to a remote Linux server without entering password in 3 \nsimple steps using ssky-keygen and ssh-copy-id as explained in this \nexample. \nssh-keygen creates the public and private keys. ssh-copy-id copies the \nlocal-host’s public key to the remote-host’s authorized_keys file. ssh-\ncopy-id also assigns proper permission to the remote-host’s home, \n~/.ssh, and ~/.ssh/authorized_keys. \nStep 1: Create public and private keys using ssh-key-gen \non local-host \njsmith@local-host$ ssh-keygen \nGenerating public/private rsa key pair. \nEnter file in which to save the key \n(/home/jsmith/.ssh/id_rsa):[Enter key] \nEnter passphrase (empty for no passphrase): [Press enter \nkey] \nEnter same passphrase again: [Pess enter key] \nYour identification has been saved in \n/home/jsmith/.ssh/id_rsa. \nYour public key has been saved in \n/home/jsmith/.ssh/id_rsa.pub. \nThe key fingerprint is: \n33:b3:fe:af:95:95:18:11:31:d5:de:96:2f:f2:35:f9 \njsmith@local-host \nStep 2: Copy the public key to remote-host using ssh-\ncopy-id \njsmith@local-host$ ssh-copy-id -i ~/.ssh/id_rsa.pub \nremote-host \njsmith@remote-host’s password: \n146\n"
},
{
"page_number": 147,
"text": "Linux 101 Hacks www.thegeekstuff.com\nNow try logging into the machine, with “ssh ‘remote-\nhost’”, and check in: \n.ssh/authorized_keys to make sure we haven’t added extra \nkeys that you weren’t expecting. \nNote: ssh-copy-id appends the keys to the remote-host’s \n.ssh/authorized_key. \nStep 3: Login to remote-host without entering the \npassword \njsmith@local-host$ ssh remote-host \n Last login: Sun Nov 16 17:22:33 2008 from 192.168.1.2 \n[Note: SSH did not ask for password.] \njsmith@remote-host$ [Note: You are on remote-host here] \nAny Questions? \nDiscuss it here: 3 Steps to Perform SSH Login Without \nPassword Using ssh-keygen & ssh-copy-id\nHack 63. Use ssh-copy-id Along With ssh-\nagent \nUsing ssh-copy-id along with the ssh-add/ssh-agent \nWhen no value is passed for the option -i and If ~/.ssh/identity.pub is not \navailable, ssh-copy-id will display the following error message. \njsmith@local-host$ ssh-copy-id -i remote-host \n147\n"
},
{
"page_number": 148,
"text": "Linux 101 Hacks www.thegeekstuff.com\n/usr/bin/ssh-copy-id: ERROR: No identities found \nIf you have loaded keys to the ssh-agent using the ssh-add, then ssh-\ncopy-id will get the keys from the ssh-agent to copy to the remote-host. \ni.e, it copies the keys provided by ssh-add -L command to the remote-\nhost, when you don’t pass option -i to the ssh-copy-id. \njsmith@local-host$ ssh-agent $SHELL \njsmith@local-host$ ssh-add -L \nThe agent has no identities. \njsmith@local-host$ ssh-add \nIdentity added: /home/jsmith/.ssh/id_rsa \n(/home/jsmith/.ssh/id_rsa) \njsmith@local-host$ ssh-add -L \nssh-rsa \nAAAAB3NzaC1yc2EAAAABIwAAAQEAsJIEILxftj8aSxMa3d8t6JvM79D \naHrtPhTYpq7kIEMUNzApnyxsHpH1tQ/Ow== \n/home/jsmith/.ssh/id_rsa \njsmith@local-host$ ssh-copy-id -i remote-host \njsmith@remote-host’s password: \nNow try logging into the machine, with “ssh ‘remote-\nhost’”, and check in: .ssh/authorized_keys to make sure we \nhaven’t added extra keys that you weren’t expecting. \n[Note: This has added the key displayed by ssh-add -L] \nThree Minor Annoyances of ssh-copy-id \nFollowing are few minor annoyances of the ssh-copy-id. \n1.\nDefault public key: ssh-copy-id uses ~/.ssh/identity.pub as the \ndefault public key file (i.e when no value is passed to option -i). \nInstead, I wish it uses id_dsa.pub, or id_rsa.pub, or identity.pub as \ndefault keys. i.e If any one of them exist, it should copy that to \n148\n"
},
{
"page_number": 149,
"text": "Linux 101 Hacks www.thegeekstuff.com\nthe remote-host. If two or three of them exist, it should copy \nidentity.pub as default. \n2.\nThe agent has no identities: When the ssh-agent is running \nand the ssh-add -L returns “The agent has no identities” (i.e no \nkeys are added to the ssh-agent), the ssh-copy-id will still copy \nthe message “The agent has no identities” to the remote-host’s \nauthorized_keys entry. \n3.\nDuplicate entry in authorized_keys: I wish ssh-copy-id \nvalidates duplicate entry on the remote-host’s authorized_keys. If \nyou execute ssh-copy-id multiple times on the local-host, it will \nkeep appending the same key on the remote-host’s \nauthorized_keys file without checking for duplicates. Even with \nduplicate entries everything works as expected. But, I would like \nto have my authorized_keys file clutter free. \nHack 64. Crontab Examples\nUsing cron you can execute a shell-script or Linux commands at a \nspecific time and date. For example a sysadmin can schedule a backup \njob that can run every day. \nHow to add a job to the cron? \n# crontab –e \n0 5 * * * /root/bin/backup.sh \nThis will execute /root/bin/backup.sh at 5 a.m every day. \nDescription of Cron fields\nFollowing is the format of the crontab file. \n{minute} {hour} {day-of-month} {month} {day-of-week} \n{full-path-to-shell-script} \n•\nminute: Allowed range 0 – 59 \n•\nhour: Allowed range 0 – 23 \n•\nday-of-month: Allowed range 0 – 31 \n149\n"
},
{
"page_number": 150,
"text": "Linux 101 Hacks www.thegeekstuff.com\n•\nmonth: Allowed range 1 – 12. 1 = January. 12 = December. \n•\nDay-of-week: Allowed range 0 – 7. Sunday is either 0 or 7. \nCrontab examples \n1. Run at 12:01 a.m. 1 minute after midnight everyday. This is a good \ntime to run backup when the system is not under load. \n1 0 * * * /root/bin/backup.sh \n2. Run backup every weekday (Mon – Fri) at 11:59 p.m. \n 59 11 * * 1,2,3,4,5 /root/bin/backup.sh \nFollowing will also do the same. \n59 11 * * 1-5 /root/bin/backup.sh \n3. Execute the command every 5 minutes. \n*/5 * * * * /root/bin/check-status.sh \n4. Execute at 1:10 p.m on 1st of every month \n10 13 1 * * /root/bin/full-backup.sh \n5. Execute 11 p.m on weekdays. \n0 23 * * 1-5 /root/bin/incremental-backup.sh \nCrontab Options \nThe following are the available options with crontab: \n•\ncrontab –e : Edit the crontab file. This will create a crontab, if it \ndoesn’t exist \n150\n"
},
{
"page_number": 151,
"text": "Linux 101 Hacks www.thegeekstuff.com\n•\ncrontab –l : Display the crontab file. \n•\ncrontab -r : Remove the crontab file. \n•\ncrontab -ir : This will prompt user before deleting a crontab. \nAdditional Cron Examples:\nLinux Crontab: 15 Awesome Cron Job Examples\nHow to Run Cron Every 5 Minutes, Seconds, Hours, Days, \nMonths\nCron Vs Anacron: How to Setup Anacron on Linux (With an \nExample)\nHack 65. Safe Reboot Of Linux Using Magic \nSysRq Key \nThe magic SysRq key is a key combination in the Linux kernel which \nallows the user to perform various low level commands regardless of the \nsystem’s state. \nIt is often used to recover from freezes, or to reboot a computer without \ncorrupting the filesystem. The key combination consists of \nAlt+SysRq+commandkey. In many systems the SysRq key is the \nprintscreen key. \nFirst, you need to enable the SysRq key, as shown below. \necho \"1\" > /proc/sys/kernel/sysrq \nList of SysRq Command Keys \nThe following are the command keys available for \nAlt+SysRq+commandkey:\n151\n"
},
{
"page_number": 152,
"text": "Linux 101 Hacks www.thegeekstuff.com\n•\n‘k’ – Kills all the process running on the current virtual console. \n•\n’s’ – This will attempt to sync all the mounted file system. \n•\n‘b’ - Immediately reboot the system, without unmounting \npartitions or syncing. \n•\n‘e’ – Sends SIGTERM to all process except init. \n•\n‘m’ – Output current memory information to the console. \n•\n‘i’ - Send the SIGKILL signal to all processes except init \n•\n‘r’ - Switch the keyboard from raw mode (the mode used by \nprograms such as X11), to XLATE mode. \n•\n’s’ – sync all mounted file system. \n•\n‘t’ - Output a list of current tasks and their information to the \nconsole. \n•\n‘u’ - Remount all mounted filesystems in readonly mode. \n•\n‘o’ – Shutdown the system immediately. \n•\n‘p’ – Print the current registers and flags to the console. \n•\n‘0-9′ - Sets the console log level, controlling which kernel \nmessages will be printed to your console. \n•\n‘f’ - Will call oom_kill to kill process which takes more memory. \n•\n‘h’ – Used to display the help. But any other keys than the above \nlisted will print help. \nWe can also do this by echoing the keys to the /proc/sysrq-trigger file. \nFor example, to re-boot a system you can perform the following. \necho \"b\" > /proc/sysrq-trigger \nPerform a Safe reboot of Linux using Magic SysRq Key \nTo perform a safe reboot of a Linux computer which hangs up, do the \nfollowing. This will avoid the fsck during the next re-booting. i.e Press \nAlt+SysRq+letter highlighted below. \n•\nunRaw (take control of keyboard back from X11)\n•\ntErminate (send SIGTERM to all processes, allowing them to \nterminate gracefully), \n152\n"
},
{
"page_number": 153,
"text": "Linux 101 Hacks www.thegeekstuff.com\n•\nkIll (send SIGILL to all processes, forcing them to terminate \nimmediately), \n•\nSync (flush data to disk), \n•\nUnmount (remount all filesystems read-only), \n•\nreBoot.\nAny Questions?\nDiscuss it here: Safe Reboot Of Linux Using Magic SysRq \nKey\nHack 66. Linux Parted Command Examples \nParted is a GNU utility, which is used to manipulate the hard disk \npartitions. \nUsing parted, you can add, delete, and edit partitions and the file \nsystems located on those partitions. You can also clone partitions. \nThis hack explains 9 practical parted command examples. \nWarning: Parted utility manipulates the hard disk partition table and \nsaves the changes immediately. So, don’t delete, modify, add, or do \nanything to your partition, if you don’t know what you are doing. You will \nlose your data! There is no undo button for your rescue! \nSelect the hard disk to be parted \nWhen you execute parted command without any argument, by default it \nselects the first hard disk drive that is available on your system. \nIn the following example, it picked /dev/sda automatically as it is the first \nhard drive in this system. \n153\n"
},
{
"page_number": 154,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# parted \nGNU Parted 2.3 \nUsing /dev/sda \nWelcome to GNU Parted! Type 'help' to view a list of \ncommands. \n(parted) \nTo choose a different hard disk, use the select command as \nshown below. \n(parted) select /dev/sdb \nIt will throw the following error message when it doesn’t find the given \nhard disk name. \nError: Error opening /dev/sdb: No medium found \nRetry/Cancel? y \nDisplay all Partitions Using print \nUsing the print command, you can view all the available partitions in the \nselected hard disk. The print command also displays hard disk properties \nsuch as model, size, sector size and partition table as shown below. \n(parted) print \nModel: ATA WDC WD5000BPVT-7 (scsi) \nDisk /dev/sda: 500GB \nSector size (logical/physical): 512B/4096B \nPartition Table: msdos \nNumber Start End Size Type Filesystem Flags \n 1 1049kB 106MB 105MB primary fat16 diag \n 2 106MB 15.8GB 15.7GB primary ntfs boot \n 3 15.8GB 266GB 251GB primary ntfs \n 4 266GB 500GB 234GB extended \n154\n"
},
{
"page_number": 155,
"text": "Linux 101 Hacks www.thegeekstuff.com\n 5 266GB 269GB 2682MB logical ext4 \n 7 269GB 270GB 524MB logical ext4 \n 8 270GB 366GB 96.8GB logical lvm \n 6 366GB 370GB 3999MB logical linux-swap(v1) \n 9 370GB 500GB 130GB logical ext4 \nCreate Primary Partition in Selected HDD Using mkpart \nmkpart command is used to create either primary or logical partition \nwith the START and END disk locations. The below example creates \npartition with size around 15GB. The START and END points passed to \nthe mkpart command are in the units of MBs. \n(parted) mkpart primary 106 16179 \nYou can also enable boot option on a partition as shown below. Linux \nreserves 1-4 or 1-3 partition number for primary partition and the \nextended partition starts from number 5. \n(parted) set 1 boot on \nCreate Logical Partition in Selected HDD Using mkpart \nUse mkpart command to create a new partition of a specific size. This \nwill create the partition of a specific type such as primary, logical or \nextended without creating the file system. \nBefore creating the partition, execute a print command to view the \ncurrent layout. \n(parted) print \nModel: ATA WDC WD5000BPVT-7 (scsi) \nDisk /dev/sda: 500GB \nSector size (logical/physical): 512B/4096B \nPartition Table: msdos \n155\n"
},
{
"page_number": 156,
"text": "Linux 101 Hacks www.thegeekstuff.com\nNumber Start End Size Type Filesystem Flags \n 1 1049kB 106MB 105MB primary fat16 diag \n 2 106MB 15.8GB 15.7GB primary ntfs boot \n 3 15.8GB 266GB 251GB primary ntfs \n 4 266GB 500GB 234GB extended \n 5 266GB 316GB 50.0GB logical ext4 \n 6 316GB 324GB 7999MB logical linux-swap(v1) \n 7 324GB 344GB 20.0GB logical ext4 \n 8 344GB 364GB 20.0GB logical ext2 \nUse mkpart to create a new logical partition with 127GB size as shown \nbelow. \n(parted) mkpart logical 372737 500000 \nExecute the print command to view the new layout as shown below. \n(parted) print \nModel: ATA WDC WD5000BPVT-7 (scsi) \nDisk /dev/sda: 500GB \nSector size (logical/physical): 512B/4096B \nPartition Table: msdos \nNumber Start End Size Type Filesystem Flags \n 1 1049kB 106MB 105MB primary fat16 diag \n 2 106MB 15.8GB 15.7GB primary ntfs boot \n 3 15.8GB 266GB 251GB primary ntfs \n 4 266GB 500GB 234GB extended \n 5 266GB 316GB 50.0GB logical ext4 \n 6 316GB 324GB 7999MB logical linux-swap(v1) \n 7 324GB 344GB 20.0GB logical ext4 \n 8 344GB 364GB 20.0GB logical ext2 \n 9 373GB 500GB 127GB logical \n156\n"
},
{
"page_number": 157,
"text": "Linux 101 Hacks www.thegeekstuff.com\n(parted) \nCreate a File System on Partition Using mkfs \nIf you use fdisk command to partition your hard disk, you need to exit \nthe fdisk utility, and use the mkfs external program to create a file \nsystem on the partition. \nHowever using parted utility, you can also create filesystem. Use the \nparted’s mkfs command to create a file system on a partition. You \nshould be careful while doing this, as all the existing data in the partition \nwill be lost during the file system creation. The supported filesystems in \nparted are ext2, mips, fat16, fat32, linux-swap, reiserfs (if libreiserfs is \ninstalled). \nLet us change the file system of partition number 8 (that is shown in the \nprint output below) from ext4 to ext2 file system. \n(parted) print \nModel: ATA WDC WD5000BPVT-7 (scsi) \nDisk /dev/sda: 500GB \nSector size (logical/physical): 512B/4096B \nPartition Table: msdos \nNumber Start End Size Type Filesystem Flags \n 1 1049kB 106MB 105MB primary fat16 diag \n 2 106MB 15.8GB 15.7GB primary ntfs boot \n 3 15.8GB 266GB 251GB primary ntfs \n 4 266GB 500GB 234GB extended \n 5 266GB 316GB 50.0GB logical ext4 \n 6 316GB 324GB 7999MB logical linux-swap(v1) \n 7 324GB 344GB 20.0GB logical ext4 \n 8 344GB 364GB 20.0GB logical ext4 \n157\n"
},
{
"page_number": 158,
"text": "Linux 101 Hacks www.thegeekstuff.com\n 9 364GB 500GB 136GB logical ext4 \nAs shown below, use the mkfs command to change the file system type \nof partition number 8. mkfs command will prompt you for partition \nnumber and file system type. \n(parted) mkfs \nWarning: The existing file system will be destroyed and \nall data on the partition will be lost. Do you want to \ncontinue? \nYes/No? y \nPartition number? 8 \nFile system type? [ext2]? ext2 \nExecute the print command again, to verify that the file system type for \npartition number 8 was changed to ex2. \n(parted) print \nModel: ATA WDC WD5000BPVT-7 (scsi) \nDisk /dev/sda: 500GB \nSector size (logical/physical): 512B/4096B \nPartition Table: msdos \nNumber Start End Size Type Filesystem Flags \n 1 1049kB 106MB 105MB primary fat16 diag \n 2 106MB 15.8GB 15.7GB primary ntfs boot \n 3 15.8GB 266GB 251GB primary ntfs \n 4 266GB 500GB 234GB extended \n 5 266GB 316GB 50.0GB logical ext4 \n 6 316GB 324GB 7999MB logical linux-swap(v1) \n 7 324GB 344GB 20.0GB logical ext4 \n 8 344GB 364GB 20.0GB logical ext2 \n 9 364GB 500GB 136GB logical ext4 \n158\n"
},
{
"page_number": 159,
"text": "Linux 101 Hacks www.thegeekstuff.com\n(parted) \nCreate Partition and Filesystem together Using mkpartfs \nUsing mkpartfs parted command, you can also create a partitions with a \nspecific filesystem. This is similar to mkpart, but with the additional \nfeature of creating file system on a partition. \nBefore mkpartfs following is the layout of the partitions. \n(parted) print \nModel: ATA WDC WD5000BPVT-7 (scsi) \nDisk /dev/sda: 500GB \nSector size (logical/physical): 512B/4096B \nPartition Table: msdos \nNumber Start End Size Type Filesystem Flags \n 1 1049kB 106MB 105MB primary fat16 diag \n 2 106MB 15.8GB 15.7GB primary ntfs boot \n 3 15.8GB 266GB 251GB primary ntfs \n 4 266GB 500GB 234GB extended \n 5 266GB 316GB 50.0GB logical ext4 \n 6 316GB 324GB 7999MB logical linux-swap(v1) \n 7 324GB 344GB 20.0GB logical ext4 \n 8 344GB 364GB 20.0GB logical \nIn the following example, mkpartfs will create a new fat32 partition of \nsize 127GB. \n(parted) mkpartfs logical fat32 372737 500000 \nAs you see below, the partition number 9 is successfully created. \n159\n"
},
{
"page_number": 160,
"text": "Linux 101 Hacks www.thegeekstuff.com\n(parted) print \nModel: ATA WDC WD5000BPVT-7 (scsi) \nDisk /dev/sda: 500GB \nSector size (logical/physical): 512B/4096B \nPartition Table: msdos \nNumber Start End Size Type Filesystem Flags \n 1 1049kB 106MB 105MB primary fat16 diag \n 2 106MB 15.8GB 15.7GB primary ntfs boot \n 3 15.8GB 266GB 251GB primary ntfs \n 4 266GB 500GB 234GB extended \n 5 266GB 316GB 50.0GB logical ext4 \n 6 316GB 324GB 7999MB logical linux-swap(v1) \n 7 324GB 344GB 20.0GB logical ext4 \n 8 344GB 364GB 20.0GB logical \n 9 373GB 500GB 127GB logical fat32 lba \n(parted) \nResize Partition from One Size to Another Using resize \nUsing resize parted command, you can increase or decrease the \npartition size of a partition as shown in the example below. \n(parted) resize 9 \nStart? [373GB]? 373GB \nEnd? [500GB]? 450GB \nAs shown above, parted command will always warn whenever you are \nattempting to do something dangerous (i.e : rm, resize, mkfs). \nThe size of partition 9 is actually reduced from 127GB to 77GB. Verify \nthat the partition is resized properly using the print command as shown \nbelow. \n160\n"
},
{
"page_number": 161,
"text": "Linux 101 Hacks www.thegeekstuff.com\n(parted) print \nModel: ATA WDC WD5000BPVT-7 (scsi) \nDisk /dev/sda: 500GB \nSector size (logical/physical): 512B/4096B \nPartition Table: msdos \nNumber Start End Size Type Filesystem Flags \n 1 1049kB 106MB 105MB primary fat16 diag \n 2 106MB 15.8GB 15.7GB primary ntfs boot \n 3 15.8GB 266GB 251GB primary ntfs \n 4 266GB 500GB 234GB extended \n 5 266GB 316GB 50.0GB logical ext4 \n 6 316GB 324GB 7999MB logical linux-swap(v1) \n 7 324GB 344GB 20.0GB logical ext4 \n 8 344GB 364GB 20.0GB logical \n 9 373GB 450GB 77.3GB logical fat32 lba \nParted allows you to type unambiguous abbreviation for commands like \n“p” for print, “sel” for select,etc. \nCopy Data from One Partition to Another Using cp \nThe entire data from one partition can be copied to another partition \nusing the cp command. You should also remember that the content of \nthe destination will be deleted before copy starts. Make sure that the \ndestination partition has enough size to hold the data from the source \npartition. \nUsing the “p” command (print) to display the current partition layout. \n(parted) p \nModel: ATA WDC WD5000BPVT-7 (scsi) \nDisk /dev/sda: 500GB \nSector size (logical/physical): 512B/4096B \n161\n"
},
{
"page_number": 162,
"text": "Linux 101 Hacks www.thegeekstuff.com\nPartition Table: msdos \nNumber Start End Size Type Filesystem Flags \n 1 1049kB 106MB 105MB primary fat16 diag \n 2 106MB 15.8GB 15.7GB primary ntfs boot \n 3 15.8GB 266GB 251GB primary ntfs \n 4 266GB 500GB 234GB extended \n 5 266GB 316GB 50.0GB logical ext4 \n 6 316GB 324GB 7999MB logical linux-swap(v1) \n 7 324GB 344GB 20.0GB logical ext4 \n 8 344GB 364GB 20.0GB logical ext2 \n 9 373GB 450GB 77.3GB logical fat32 lba \n10 461GB 500GB 39.2GB logical ext2 \nIt is recommended to unmount both source and destination partition \nbefore doing copy. In this example we are going to copy the content \nfrom partition 8 to partition 10. \nThe following shows the content of the corresponding partitions before \ncopy. \n# mount /dev/sda8 /mnt \n# cd /mnt \n# ls -l \ntotal 52 \n-rw-r--r-- 1 root root 0 2011-09-26 22:52 part8 \n-rw-r--r-- 1 root root 20 2011-09-26 22:52 test.txt \n# umount /mnt \n# mount /dev/sda10 /mnt \n# cd /mnt \n# ls -l \ntotal 48 \n162\n"
},
{
"page_number": 163,
"text": "Linux 101 Hacks www.thegeekstuff.com\n-rw-r--r-- 1 root root 0 2011-09-26 22:52 part10 \nUse the parted cp command to copy partition 8 to partition 10 as shown \nbelow. \n(parted) cp 8 10 \ngrowing file system... 95% (time left 00:38)\nThe following shows the content of the partition 10 after the copy. As \nyou see below, the content of partition 8 is copied over (overwritten) to \nthe partition 10. \n # mount /dev/sda10 /mnt \n# cd /mnt \n# ls -l \ntotal 52 \n-rw-r--r-- 1 root root 0 2011-09-26 22:52 part8 \n-rw-r--r-- 1 root root 20 2011-09-26 22:52 test.txt \nNote: When you copy across partitions of different filesystem(for \nexample src : ext2 and dst : ext4), the destination partition’s file system \nis actually converted to the file system of source partition (i.e : ext2) . \nRemove Partition from a Selected Hard Disk Using rm \nTo delete an unwanted or unused partition, use the parted rm command \nand specify the partition number as shown below. \n(parted) rm \nPartition number? 9 \n(parted) \nAs you see below, the partition number 9 is now deleted. \n163\n"
},
{
"page_number": 164,
"text": "Linux 101 Hacks www.thegeekstuff.com\n(parted) print \nModel: ATA WDC WD5000BPVT-7 (scsi) \nDisk /dev/sda: 500GB \nSector size (logical/physical): 512B/4096B \nPartition Table: msdos \nNumber Start End Size Type Filesystem Flags \n 1 1049kB 106MB 105MB primary fat16 diag \n 2 106MB 15.8GB 15.7GB primary ntfs boot \n 3 15.8GB 266GB 251GB primary ntfs \n 4 266GB 500GB 23GB extended \n 5 266GB 316GB 50.0GB logical ext4 \n 6 316GB 324GB 7999MB logical linux-swap(v1) \n 7 324GB 344GB 20.0GB logical ext4 \n 8 344GB 364GB 20.0GB logical ext2\nAny Questions?\nDiscuss it here: 9 Linux Parted Command Examples – \nmkpart, mkpartfs, resize partitions\nHack 67. Rsync Command Examples \nrsync stands for remote sync. \nrsync is used to perform the backup operation in UNIX / Linux. \nrsync utility is used to synchronize the files and directories from one \nlocation to another in an effective way. Backup location could be on local \nserver or on remote server. \n164\n"
},
{
"page_number": 165,
"text": "Linux 101 Hacks www.thegeekstuff.com\nImportant features of rsync \n•\nSpeed: First time, rsync replicates the whole content between \nthe source and destination directories. Next time, rsync transfers \nonly the changed blocks or bytes to the destination location, \nwhich makes the transfer really fast. \n•\nSecurity: rsync allows encryption of data using ssh protocol \nduring transfer. \n•\nLess Bandwidth: rsync uses compression and decompression of \ndata block by block at the sending and receiving end \nrespectively. So the bandwidth used by rsync will be always less \ncompared to other file transfer protocols. \n•\nPrivileges: No special privileges are required to install and \nexecute rsync \nSyntax :\n$ rsync options source destination \nSource and destination could be either local or remote. In case of \nremote, specify the login name, remote server name and location. \nSynchronize Two Directories in a Local Server \nTo sync two directories in a local computer, use the following rsync -zvr \ncommand. \n$ rsync -zvr /var/opt/installation/inventory/ /root/temp \nbuilding file list ... done \nsva.xml \nsvB.xml \n. \nsent 26385 bytes received 1098 bytes 54966.00 bytes/sec \ntotal size is 44867 speedup is 1.63 \nIn the above rsync example: \n165\n"
},
{
"page_number": 166,
"text": "Linux 101 Hacks www.thegeekstuff.com\n•\n-z is to enable compression \n•\n-v verbose \n•\n-r indicates recursive \nNow let us see the timestamp on one of the files that was copied from \nsource to destination. As you see below, rsync didn’t preserve \ntimestamps during sync. \n$ ls -l /var/opt/installation/inventory/sva.xml \n/root/temp/sva.xml \n-r--r--r-- 1 bin bin 949 Jun 18 2009 \n/var/opt/installation/inventory/sva.xml \n-r--r--r-- 1 root bin 949 Sep 2 2009 /root/temp/sva.xml \nPreserve timestamps during Sync using rsync -a \nrsync option -a indicates archive mode. -a option does the following, \n•\nRecursive mode \n•\nPreserves symbolic links \n•\nPreserves permissions \n•\nPreserves timestamp \n•\nPreserves owner and group \nNow, executing the same command provided in example 1 (But with the \nrsync option -a) as shown below: \n$ rsync -azv /var/opt/installation/inventory/ /root/temp/ \nbuilding file list ... done \n./ \nsva.xml \nsvB.xml \n. \nsent 26499 bytes received 1104 bytes 55206.00 bytes/sec \ntotal size is 44867 speedup is 1.63 \n166\n"
},
{
"page_number": 167,
"text": "Linux 101 Hacks www.thegeekstuff.com\nAs you see below, rsync preserved timestamps during sync. \n$ ls -l /var/opt/installation/inventory/sva.xml \n/root/temp/sva.xml \n-r--r--r-- 1 root bin 949 Jun 18 2009 \n/var/opt/installation/inventory/sva.xml \n-r--r--r-- 1 root bin 949 Jun 18 2009 \n/root/temp/sva.xml \nSynchronize Only One File \nTo copy only one file, specify the file name to rsync command, as shown \nbelow. \n$ rsync -v /var/lib/rpm/Pubkeys /root/temp/ \nPubkeys \nsent 42 bytes received 12380 bytes 3549.14 bytes/sec \ntotal size is 12288 speedup is 0.99 \nSynchronize Files From Local to Remote \nrsync allows you to synchronize files/directories between the local and \nremote system. \n$ rsync -avz /root/temp/ \nthegeekstuff@192.168.200.10:/home/thegeekstuff/temp/ \nPassword: \nbuilding file list ... done \n./ \nrpm/ \nrpm/Basenames \nrpm/Conflictname \nsent 15810261 bytes received 412 bytes 2432411.23 \nbytes/sec \n167\n"
},
{
"page_number": 168,
"text": "Linux 101 Hacks www.thegeekstuff.com\ntotal size is 45305958 speedup is 2.87 \nWhile doing synchronization with the remote server, you need to specify \nusername and ip-address of the remote server. You should also specify \nthe destination directory on the remote server. The format is \nusername@machinename:path \nAs you see above, it asks for password while doing rsync from local to \nremote server. \nSometimes you don’t want to enter the password while backing up files \nfrom local to remote server. For example, If you have a backup shell \nscript, that copies files from local to remote server using rsync, you need \nthe ability to rsync without having to enter the password. \nTo do that, setup ssh password less login as we explained earlier. \nSynchronize Files From Remote to Local \nWhen you want to synchronize files from remote to local, specify remote \npath in source and local path in target as shown below. \n$ rsync -avz thegeekstuff@192.168.200.10:/var/lib/rpm \n/root/temp \nPassword: \nreceiving file list ... done \nrpm/ \nrpm/Basenames \n. \nsent 406 bytes received 15810230 bytes 2432405.54 \nbytes/sec \ntotal size is 45305958 speedup is 2.87 \n168\n"
},
{
"page_number": 169,
"text": "Linux 101 Hacks www.thegeekstuff.com\nAdditional RSYNC Examples:\nHow to Backup Linux? 15 rsync Command Examples\n6 rsync Examples to Exclude Multiple Files and \nDirectories using exclude-from\nHack 68. Chkconfig Command Examples\nChkconfig command is used to setup, view, or change services that are \nconfigured to start automatically during the system startup. \nThis hack contains 7 practical examples that explains how to use the \nchkconfig command. \nCheck Service Startup status from Shell Script \nWhen you execute chkconfig command only with the service name, it \nreturns true if the service is configured for startup. The following code \nsnippet shows how to check whether a service is configured for startup \nor not from a shell script. \n# vi check.sh \nchkconfig network && echo \"Network service is configured\" \nchkconfig junk && echo \"Junk service is configured\" \n# ./check.sh \nNetwork service is configured \nYou can also specifically check whether it is configured for a particular \nrun level or not. \n# vi check1.sh \nchkconfig network --level 3 && echo \"Network service is \nconfigured for level 3\" \n169\n"
},
{
"page_number": 170,
"text": "Linux 101 Hacks www.thegeekstuff.com\nchkconfig network --level 1 && echo \"Network service is \nconfigured for level 1\" \n# ./check1.sh \nNetwork service is configured for level 3 \nView Current Status of Startup Services \nThe –list option displays all the services with the current startup \nconfiguration status. \n# chkconfig --list \nabrtd 0:off 1:off 2:off 3:on 4:off 5:on 6:off \nacpid 0:off 1:off 2:off 3:off 4:off 5:off 6:off \natd 0:off 1:off 2:off 3:on 4:on 5:on 6:off \n... \nTo view only the services that are configured to be started during system \nstartup, do the following. Please note that this assumes that your \nsystem startup level is 3. \nchkconfig --list | grep 3:on \nTo view the startup configuration of a particular service, grep the output \nof ‘chkconfig –list’ for that service. \nchkconfig --list | grep network \nAdd a new Service to the Startup \nUse –add option to add a specific service to the list of services that will \nbe started during system reboot. \nThe following example shows how to add a new service (for example, \niptables) to the list of services that needs to be started. The ‘chkconfig –\nadd’ command will also turn on level 2, 3, 4 and 5 automatically as \nshown below. \n170\n"
},
{
"page_number": 171,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# chkconfig --list | grep iptables \n# chkconfig --add iptables \n# chkconfig --list | grep iptables \niptables 0:off 1:off 2:on 3:on 4:on \n5:on 6:off \nNote: “chkconfig –add” only adds an existing service to the list of \nstartup. If the service doesn’t exist, you should first install it before \nadding it to the system startup list. While this is pretty obvious, it is \nworth to mention it, as a newbie might make this mistake. \nRemove a Service From Startup List \nThe following example shows that ip6tables services is configured for \nstartup. \n# chkconfig --list | grep ip6tables \nip6tables 0:off 1:off 2:off 3:on 4:off 5:off 6:off \nTo remove it from the startup list, use the –del option as shown below. \n# chkconfig --del ip6tables \n# chkconfig --list | grep ip6tables \nTurn-on or Turn-off a Service for a Selected Run Level \nSometimes you might not want to delete the whole service. Instead, you \nmight just want to turn the flag on or off for a particular run level (for a \nparticular service). \nThe following example will turn off nfserver service for level 5 \n# chkconfig --level 5 nfsserver off \n171\n"
},
{
"page_number": 172,
"text": "Linux 101 Hacks www.thegeekstuff.com\nYou can also combine multiple levels. The following example will turn off \nnfsserver for both level 3 and 5. \n# chkconfig --level 35 nfsserver off \nScript Files under rc.d Subdirectories \nWhenever you add or remove a service from chkconfig control, it does \nthe following under the /etc/rc.d sub-directories. \n \nWhen chkconfig –add command is executed, it creates a symbolic link \nfile to start and stop the service under corresponding rc directory. \nWhen chkconfig –del command is executed, it removes the symbolic link \nfile from the corresponding rc directory. \nThe following example shows that xinetd is enabled for both run level 3 \nand 5. \nSo, xinetd will have two files under rc3.d directory, and two files under \nrc5.d directory. The file that starts with K is used during shutdown (K \nstands for kill). The file that starts with S is used during startup (S stands \nfor start). \n# chkconfig --list | grep xinetd \nxinetd 0:off 1:off 2:off 3:on 4:off 5:on 6:off \nxinetd based services: \n# cd /etc/rc.d/rc3.d \n# ls | grep xinetd \nK08xinetd \nS14xinetd \n# cd /etc/rc.d/rc5.d \n172\n"
},
{
"page_number": 173,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# ls | grep xinetd \nK08xinetd \nS14xinetd \nrcx.d Directory Changes for Add Operation \nWhen you add a new service to chkconfig control, the default run levels \nfor that service will be turned on automatically, and files will be created \nunder the corresponding rcx directories. \nFor example, if the nfsserver service doesn’t exist in the chkconfig \ncontrol, no nfsserver service startup files would be present under \n/etc/rc.d/rc*.d directories as shown below. \n# chkconfig --list | grep nfsserver \nnfsserver 0:off 1:off 2:off 3:off 4:off 5:off 6:off \n# ls /etc/rc.d/rc3.d | grep nfsserver \n# ls /etc/rc.d/rc5.d | grep nfsserver \nAfter you add the nfsserver service, you’ll see the symbolic links under \nthese directories. \n# chkconfig --add nfsserver \nnfsserver 0:off 1:off 2:off 3:on 4:off 5:on 6:off \n# cd /etc/rc.d/rc3.d \n# ls -l | grep nfsserver \nlrwxrwxrwx 1 root root 12 2011-06-18 00:52 K08nfsserver -> \n../nfsserver \nlrwxrwxrwx 1 root root 12 2011-06-18 00:52 S14nfsserver -> \n../nfsserver \n173\n"
},
{
"page_number": 174,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# cd /etc/rc.d/rc5.d \n# ls -l | grep nfsserver \nlrwxrwxrwx 1 root root 12 2011-06-18 00:52 K08nfsserver -> \n../nfsserver \nlrwxrwxrwx 1 root root 12 2011-06-18 00:52 S14nfsserver -> \n../nfsserver \nWhen you turn off the service either using –del option or –level option, \nthe corresponding symbolic link file under rcx.d directory will be deleted \nas shown below. \n# chkconfig --level 5 nfsserver off \n# ls /etc/rc.d/rc5.d | grep nfsserver\nAny Questions?\nDiscuss it here: 7 Linux chkconfig Command Examples – \nAdd, Remove, View, Change Services\nHack 69. How to Setup Anacron\nAnacron is the cron for desktops and laptops. \nAnacron does not expect the system to be running 24 x 7 like a server. \nWhen you want a background job to be executed automatically on a \nmachine that is not running 24 x 7, you should use anacron. \nFor example, if you have a backup script scheduled everyday at 11 PM \nas a regular cron job, and if your laptop is not up at 11 PM, your backup \njob will not be executed. \n174\n"
},
{
"page_number": 175,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHowever, if you have the same job scheduled in anacron, you can be \nsure that it will be executed once the laptop come back up. \nAnacrontab Format \nJust like how cron has /etc/crontab, anacron has /etc/anacrontab. \n/etc/anacrontab file has the anacron jobs mentioned in the following \nformat. \nperiod delay job-identifier command \nField 1 is Recurrence period: This is a numeric value that specifies \nthe number of days. \n•\n1 – daily \n•\n7 – weekly \n•\n30 – monthly \n•\nN – This can be any numeric value. N indicates number of days \n•\nNote: You can also use ‘@monthly’ for a job that needs to be \nexecuted monthly. \nField 2 is Delay: This indicates the delay in minutes. i.e X number of \nminutes anacron should wait before executing the job after the the \nmachine starts. \nField 3 is Job identifier: It is the name for the job’s timestamp file. It \nshould be unique for each job. This will be available as a file under the \n/var/spool/anacron directory. This file will contain a single line that \nindicates the last time when this job was executed. \n# ls -1 /var/spool/anacron/ \ntest.daily \ncron.daily \ncron.monthly \ncron.weekly \n175\n"
},
{
"page_number": 176,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# cat /var/spool/anacron/test.daily \n20110507 \nField 4 is command: Command or shell script that needs to be \nexecuted. \nJust like shell scripts, comments inside anacrontab file starts with # \nAnacron Example \nThe following example executes the /home/sathiya/backup.sh script \nonce in every 7 days. \nOn the day when the backup.sh job is supposed to executed, if the \nsystem is down for some reason, anacron will execute the backup.sh \nscript 15 minutes after the system comes back up (without having to \nwait for another 7 days). \n# cat /etc/anacrontab \n7 15 test.daily /bin/sh \n/home/sathiya/backup.sh \nSTART_HOURS_RANGE and RANDOM_DELAY \nThe above example indicates that the backup.sh script should be \nexecuted every day, with a delay of 15 mins. i.e When the laptop was \nstarted, executed it only after 15 minutes. \nWhat happens when the laptop or desktop was not shutdown? When \ndoes the job gets executed? This is specified by the \nSTART_HOURS_RANGE environment variable in the /etc/anacrontab file. \nBy default this is set to 3-22 in the file. This indicates the time range \nfrom 3 a.m to 10 p.m. \n176\n"
},
{
"page_number": 177,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# grep START /etc/anacrontab \nSTART_HOURS_RANGE=3-22 \nOn top of the user defined delay specified in the 2nd field of the \n/etc/anacrontab file, anacron also randomly adds x number of minutes. \nThe x is defined by the RANDOM_DELAY variable in the /etc/anacrontab \nfile. \nBy default this is set to 45 in the file. This means that anacron will add x \nminutes (randomly picked from 0 and 45), and add this to the user \ndefined delay. \n# grep RANDOM /etc/anacrontab \nRANDOM_DELAY=45 \nCron Vs Anacron \nCron and anacron has its own advantages and disadvantages. \nDepending on your requirement, use one of them. \nCron\nAnacron\nMinimum granularity is \nminute (i.e Jobs can be \nscheduled to be executed \nevery minute)\nMinimum granularity is \nonly in days\nCron job can be scheduled by \nany normal user ( if not \nrestricted by super user \nAnacron can be used only \nby super user ( but there \nare workarounds to make it \nusable by normal user )\nCron expects system to be \nrunning 24 x 7. If a job is \nscheduled, and system is \ndown during that time, job is \nnot executed.\nAnacron doesn’t expect \nsystem to be running 24 x \n7. If a job is scheduled, and \nsystem is down during that \ntime, it start the jobs when \nthe system comes back up.\nIdeal for servers\nIdeal for desktops and \nlaptops \n177\n"
},
{
"page_number": 178,
"text": "Linux 101 Hacks www.thegeekstuff.com\nUse cron when a job has to be \nexecuted at a particular hour \nand minute\nUse anacron when a job \nhas to be executed \nirrespective of hour and \nminute\nAny Questions?\nDiscuss it here: Cron Vs Anacron: How to Setup Anacron \non Linux (With an Example)\nHack 70. IPTables Rules Examples \nDelete Existing Rules \nBefore you start building new set of rules, you might want to clean-up all \nthe default rules, and existing rules. Use the iptables flush command as \nshown below to do this. \niptables -F \n(or) \niptables --flush \nSet Default Chain Policies \nThe default chain policy is ACCEPT. Change this to DROP for all INPUT, \nFORWARD, and OUTPUT chains as shown below. \niptables -P INPUT DROP \niptables -P FORWARD DROP \niptables -P OUTPUT DROP \nWhen you make both INPUT, and OUTPUT chain’s default policy as \nDROP, for every firewall rule requirement you have, you should define \ntwo rules. i.e one for incoming and one for outgoing. \n178\n"
},
{
"page_number": 179,
"text": "Linux 101 Hacks www.thegeekstuff.com\nIn all our examples below, we have two rules for each scenario, as we’ve \nset DROP as default policy for both INPUT and OUTPUT chain. \nIf you trust your internal users, you can omit the last line above. i.e Do \nnot DROP all outgoing packets by default. In that case, for every firewall \nrule requirement you have, you just have to define only one rule. i.e \ndefine rule only for incoming, as the outgoing is ACCEPT for all packets. \nBlock a Specific ip-address \nBefore we proceed further will other examples, if you want to block a \nspecific ip-address, you should do that first as shown below. Change the \n“x.x.x.x” in the following example to the specific ip-address that you like \nto block. \nBLOCK_THIS_IP=\"x.x.x.x\" \niptables -A INPUT -s \"$BLOCK_THIS_IP\" -j DROP \nThis is helpful when you find some strange activities from a specific ip-\naddress in your log files, and you want to temporarily block that ip-\naddress while you do further research. \nYou can also use one of the following variations, which blocks only TCP \ntraffic on eth0 connection for this ip-address. \niptables -A INPUT -i eth0 -s \"$BLOCK_THIS_IP\" -j DROP \niptables -A INPUT -i eth0 -p tcp -s \"$BLOCK_THIS_IP\" -j \nDROP \nAllow ALL Incoming SSH \nThe following rules allow ALL incoming ssh connections on eth0 \ninterface. \niptables -A INPUT -i eth0 -p tcp --dport 22 -m state \n--state NEW,ESTABLISHED -j ACCEPT \niptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state \n--state ESTABLISHED -j ACCEPT \n179\n"
},
{
"page_number": 180,
"text": "Linux 101 Hacks www.thegeekstuff.com\nAllow Incoming SSH only from a Specific Network \nThe following rules allow incoming ssh connections only from \n192.168.100.X network. \niptables -A INPUT -i eth0 -p tcp -s 192.168.100.0/24 \n--dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT \niptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state \n--state ESTABLISHED -j ACCEPT \nIn the above example, instead of /24, you can also use the full subnet \nmask. i.e “192.168.100.0/255.255.255.0″. \nAdditional IPTables Examples:\n25 Most Frequently Used Linux IPTables Rules Examples\nIPTables Tables, Chains, Rules Fundamentals\nHow to Add Firewall Rules\nIncoming and Outgoing Rule Examples\n180\n"
},
{
"page_number": 181,
"text": "Linux 101 Hacks www.thegeekstuff.com\nChapter 9: Install Packages\nHack 71. Yum Command Examples\nInstalling, removing, and updating packages is a typical activity on \nLinux. Most of the Linux distributions provides some kind of package \nmanager utility. For example, apt-get, dpkg, rpm, yum, etc. \nOn some Linux distributions, yum is the default package manager. \nYum stands for Yellowdog Updater Modified. \nInstall a package using yum install \nTo install a package, do ‘yum install packagename’. This will also identify \nthe dependencies automatically and install them. \nThe following example installs postgresql package. \n# yum install postgresql.x86_64 \nResolving Dependencies \nInstall 2 Package(s) \nIs this ok [y/N]: y \nRunning Transaction \nInstalling : postgresql-libs-9.0.4-5.fc15.x86_64 1/2 \nInstalling : postgresql-9.0.4-5.fc15.x86_64 2/2 \nBy default ‘yum install’, will prompt you to accept or decline before \ninstalling the packages. If you want yum to install automatically without \nprompting, use -y option as shown below. \n# yum -y install postgresql.x86_64 \n181\n"
},
{
"page_number": 182,
"text": "Linux 101 Hacks www.thegeekstuff.com\nUninstall a package using yum remove \nTo remove a package (along with all its dependencies), use ‘yum remove \npackage’ as shown below. \n# yum remove postgresql.x86_64 \nPackage postgresql.x86_64 0:9.0.4-5.fc15 will be erased \nIs this ok [y/N]: y \nRunning Transaction \n Erasing : postgresql-9.0.4-5.fc15.x86_64 1/1 \nUpgrade an existing package using yum update \nIf you have a older version of a package, use ‘yum update package’ to \nupgrade it to the latest current version. This will also identify and install \nall required dependencies. \n# yum update postgresql.x86_64 \nSearch for a package to be installed using yum search \nIf you don’t know the exact package name to be installed, use ‘yum \nsearch keyword’, which will search all the packages that matches the \n‘keyword’ and display it. \nThe following examples searches the yum repository for all the packages \nthat matches the keyword ‘firefox’ and lists the available packages. \n# yum search firefox \nLoaded plugins: langpacks, presto, refresh-packagekit \n============== N/S Matched: firefox ====================== \nfirefox.x86_64 : Mozilla Firefox Web browser \ngnome-do-plugins-firefox.x86_64 \nmozilla-firetray-firefox.x86_64 \nmozilla-adblockplus.noarch : Mozilla Firefox extension\nmozilla-noscript.noarch : Mozilla Firefox extension\n182\n"
},
{
"page_number": 183,
"text": "Linux 101 Hacks www.thegeekstuff.com\nName and summary matches only, use \"search all\" for everything. \nDisplay additional information about a package using yum \ninfo \nOnce you search for a package using yum search, you can use ‘yum info \npackage’ to view additional information about the package. \nThe following examples displays additional information about the \nsamba-common package. \n# yum info samba-common.i686 \nLoaded plugins: langpacks, presto, refresh-packagekit \nAvailable Packages \nName : samba-common \nArch : i686 \nEpoch : 1 \nVersion : 3.5.11 \nRelease : 71.fc15.1 \nSize : 9.9 M \nRepo : updates \nSummary : Files used by both Samba servers and clients \nURL : http://www.samba.org/ \nLicense : GPLv3+ and LGPLv3+ \nDescription : Samba-common provides files necessary for \nboth the server and client\nAdditional YUM Examples:\n15 Linux Yum Command Examples – Install, Uninstall, \nUpdate Packages\n183\n"
},
{
"page_number": 184,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 72. RPM Command Examples\nRPM command is used for installing, uninstalling, upgrading, querying, \nlisting, and checking RPM packages on your Linux system. \nRPM stands for Red Hat Package Manager. \nWith root privilege, you can use the rpm command with appropriate \noptions to manage the RPM software packages. \nLet us take an rpm of Mysql Client and run through all our examples. \nInstalling a RPM package Using rpm -ivh \nRPM filename has packagename, version, release and architecture \nname. \nFor example, In the MySQL-client-3.23.57-1.i386.rpm file: \n•\nMySQL-client – Package Name \n•\n3.23.57 – Version \n•\n1 – Release \n•\ni386 – Architecture \nWhen you install a RPM, it checks whether your system is suitable for \nthe software the RPM package contains, figures out where to install the \nfiles located inside the rpm package, installs them on your system, and \nadds that piece of software into its database of installed RPM packages. \nThe following rpm command installs Mysql client package. \n# rpm -ivh MySQL-client-3.23.57-1.i386.rpm \nPreparing...################################### [100%] \n 1:MySQL-client############################## [100%] \n184\n"
},
{
"page_number": 185,
"text": "Linux 101 Hacks www.thegeekstuff.com\nrpm command and options \n•\n-i : install a package \n•\n-v : verbose \n•\n-h : print hash marks as the package archive is unpacked. \nYou can also use dpkg on Debian, pkgadd on Solaris, depot on HP-UX to \ninstall packages. \nQuery all the RPM Packages using rpm -qa \nYou can use rpm command to query all the packages installed in your \nsystem. \n# rpm -qa \ncdrecord-2.01-10.7.el5 \nbluez-libs-3.7-1.1 \nsetarch-2.0-1.1 \n. \n. \n•\n-q query operation \n•\n-a queries all installed packages \nTo identify whether a particular rpm package is installed on your system, \ncombine rpm and grep command as shown below. Following command \nchecks whether cdrecord package is installed on your system. \n# rpm -qa | grep 'cdrecord' \nQuery a Particular RPM Package using rpm -q \nThe above example lists all currently installed package. After installation \nof a package to check the installation, you can query a particular \npackage and verify as shown below. \n# rpm -q MySQL-client \nMySQL-client-3.23.57-1 \n185\n"
},
{
"page_number": 186,
"text": "Linux 101 Hacks www.thegeekstuff.com\n \n# rpm -q MySQL \npackage MySQL is not installed \nNote: To query a package, you should specify the exact package name. If \nthe package name is incorrect, then rpm command will report that the \npackage is not installed. \nQuery RPM Packages in a various format using rpm –\nqueryformat \nRpm command provides an option –queryformat, which allows you to \ngive the header tag names, to list the packages. Enclose the header tag \nwith in {}. \n# rpm -qa --queryformat '%{name-%{version}-%{release} %\n{size}\\n' \ncdrecord-2.01-10.7 12324 \nbluez-libs-3.7-1.1 5634 \nsetarch-2.0-1.1 235563 \n. \n. \nWhich RPM package does a file belong to? – Use rpm -qf \nLet us say, you have list of files and you would want to know which \npackage owns all these files. rpm command has options to achieve this. \nThe following example shows that /usr/bin/mysqlaccess file is part of the \nMySQL-client-3.23.57-1 rpm. \n# rpm -qf /usr/bin/mysqlaccess \nMySQL-client-3.23.57-1 \n186\n"
},
{
"page_number": 187,
"text": "Linux 101 Hacks www.thegeekstuff.com\nLocate documentation of a package that owns file using \nrpm -qdf \nUse the following to know the list of documentations, for a package that \nowns a file. The following command, gives the location of all the manual \npages related to mysql package. \n# rpm -qdf /usr/bin/mysqlaccess \n/usr/share/man/man1/mysql.1.gz \n/usr/share/man/man1/mysqlaccess.1.gz \n/usr/share/man/man1/mysqladmin.1.gz \n/usr/share/man/man1/mysqldump.1.gz \n/usr/share/man/man1/mysqlshow.1.gz \n•\n-d : refers documentation. \nInformation about Installed RPM Package using rpm -qip \nrpm command provides a lot of information about the installed \npackages. \n# rpm -qip MySQL-client-3.23.57-1.i386.rpm \nName : MySQL-client Relocations: (not relocatable) \nVersion : 3.23.57 Vendor: MySQL AB \nRelease : 1 Build Date: Mon 09 Jun 2003\nInstall Date: Build Host: build.mysql.com \nGroup : Applications/Databases\nSize : 5305109 License: GPL / LGPL \nSignature : (none) \nPackager : Lenz Grimmer \nURL : http://www.mysql.com/ \nSummary : MySQL - Client \nDescription : This package is a standard MySQL client.\n•\n-i : view information about an rpm \n•\n-p : specify a package name \n187\n"
},
{
"page_number": 188,
"text": "Linux 101 Hacks www.thegeekstuff.com\nList all the Files in a Package using rpm -qlp \nTo list the content of a RPM package, use the following command, which \nwill list out the files without extracting into the local directory folder. \n$ rpm -qlp ovpc-2.1.10.rpm \n/usr/bin/mysqlaccess \n/usr/bin/mysqldata \n/usr/bin/mysqlperm \n. \n. \n/usr/bin/mysqladmin \n•\nq : query the rpm file \n•\nl : list the files in the package \n•\np : specify the package name \nList the Dependency Packages using rpm -qRP \nTo view the list of packages on which this package depends, \n# rpm -qRp MySQL-client-3.23.57-1.i386.rpm \n/bin/sh \n/usr/bin/perl \nAdditional RPM Examples:\nRPM Command: 15 Examples to Install, Uninstall, Upgrade, \nQuery RPM Packages\nHack 73. apt-* Command Examples\nDebian based systems (including Ubuntu) uses apt-* commands for \nmanaging packages from the command line. \n188\n"
},
{
"page_number": 189,
"text": "Linux 101 Hacks www.thegeekstuff.com\nThis hack, using Apache 2 installation as an example, explains how to \nuse apt-* commands to view, install, remove, or upgrade packages. \napt-cache search: Search Repository Using Package Name \nIf you are installing Apache 2, you may guess that the package name is \napache2. To verify whether it is a valid package name, you may want to \nsearch the repository for that particular package name as shown below. \nThe following example shows how to search the repository for a specific \npackage name. \n$ apt-cache search ^apache2$ \napache2 - Apache HTTP Server metapackage \ndpkg -l: Is the Package Already Installed? \nBefore installing a package, you may want to make sure it is not already \ninstalled as shown below using dpkg -l command. \n$ dpkg -l | grep -i apache \napt-get install: Install a Package \nFinally, install the package using “apt-get install” as shown below. \n$ sudo apt-get install apache2 \n[sudo] password for ramesh: \nThe following NEW packages will be installed: \n apache2 apache2-mpm-worker apache2-utils \n apache2.2-common libapr1 libaprutil1 libpq5 \n0 upgraded, 7 newly installed, 0 to remove and 26 not \nupgraded. \n189\n"
},
{
"page_number": 190,
"text": "Linux 101 Hacks www.thegeekstuff.com\n apt-get remove: Delete a Package \nUse “apt-get purge” or “apt-get remove” to delete a package as shown \nbelow. \n$ sudo apt-get purge apache2 \n(or) \n$ sudo apt-get remove apache2 \nAdditional apt-* Command Examples:\nHow To Manage Packages Using apt-get, apt-cache, apt-\nfile and dpkg Commands ( With 13 Practical Examples )\nHack 74. Install from Source\nSometimes you might have to download the source code of an \napplication and install it from the source.\nThis hack explains how to install from source. You should always refer to \nthe INSTALL or README file that is located in the downloaded application \npackage for any application specific installation instructions. \nDownload and unzip the package \nTypically the source code you download will be compressed in a *.tar.gz \nor *.tar.bz2 format.\nIf the source code you've downloaded is in the format application.tar.gz, \nuse the following command to uncompress it .\ntar xvfz application.tar.gz \n \n190\n"
},
{
"page_number": 191,
"text": "Linux 101 Hacks www.thegeekstuff.com\nIf the source code you've downloaded is in the format \napplication.tar.bz2, use the following command to uncompress it.\ntar xvfj application.tar.bz2 \nConfigure \nOnce you uncompress the source tar file, it will create a subdirectory in \nthe name of the application. CD to this directory. \ncd application \nDo a ./configure --help which will display all application specific \nconfiguration options that are available to you. \n./configure --help \nIn most cases, you can just do ./configure which will use all default \nvalues to perform the configuration. This will perform necessary pre-req \nchecks. This will also generate the Makefile required for the installation. \n./configure \nMake and Install \nMake command will use the Makefile created from the above step and \ncreate the application binary executable. \nmake \nFinally, do 'make install' which will install the application in the \nappropriate location. \nmake install\n191\n"
},
{
"page_number": 192,
"text": "Linux 101 Hacks www.thegeekstuff.com\nChapter 10: LAMP Stack\nHack 75. Install Apache 2 with SSL\nThis hack provides step by step instructions on how to install Apache 2 \nwith mod_ssl. \nI prefer to install Apache from source, as it gives me more flexibility on \nexactly what modules I want to enable or disable, and I can also upgrade \nor apply patch immediately after it is released by the Apache \nfoundation. \nDownload Apache \nDownload Apache from httpd.apache.org. The current stable release is \n2.2.17. \nOnce you get the direct URL to download the latest stable version of \nApache, use wget as shown below to download it directly to you server. \ncd ~ \nwget http://www.eng.lsu.edu/mirrors/apache//httpd/httpd-\n2.2.17.tar.gz \ntar xvfz httpd-2.2.17.tar.gz \nInstall Apache with SSL/TLS \nView all available Apache installation and configuration options as shown \nbelow. \ncd httpd-2.2.17 \n./configure --help \nTo install an Apache module, you would typically say –enable-{module-\nname}. For example, to install SSL with Apache, it is –enable-ssl. To \ninstall ldap module, it is –enable-ldap. \n192\n"
},
{
"page_number": 193,
"text": "Linux 101 Hacks www.thegeekstuff.com\n \nTo uninstall any default module that comes with Apache, you would \ntypically say –disable-{module-name}. For example, to disable basic \nauthentication in Apache, it is –disable-auth-basic \nIn this example, we will install Apache with all default modules, with \naddition of –enable-ssl (to install mod_ssl for SSL support), and –enable-\nso, which helps to load modules in Apache during run-time via the \nDynamic Shared Object (DSO) mechanism, rather than requiring a \nrecompilation. \n./configure --enable-ssl --enable-so \nmake \nmake install \nNote: By default the above installs Apache under /usr/local/apache2. If \nyou like to change this location, use –prefix option in the ./configure. \nEnable SSL in httpd.conf \nApache configuration file httpd.conf is located under \n/usr/local/apache2/conf. \nUncomment the httpd-ssl.conf Include line in the \n/usr/local/apache2/conf/httpd.conf file. \n# vi /usr/local/apache2/conf/httpd.conf \nInclude conf/extra/httpd-ssl.conf \nView the httpd-ssl.conf to review all the default SSL configurations. For \nmost cases, you don’t need to modify anything in this file. \nvi /usr/local/apache2/conf/extra/httpd-ssl.conf \nThe SSL certificate and key are required before we start the Apache. The \nserver.crt and server.key file mentioned in the httpd-ssl.conf needs to be \ncreated before we move forward. \n193\n"
},
{
"page_number": 194,
"text": "Linux 101 Hacks www.thegeekstuff.com\n # egrep 'server.crt|server.key' httpd-ssl.conf \nSSLCertificateFile \"/usr/local/apache2/conf/server.crt\" \nSSLCertificateKeyFile \"/usr/local/apache2/conf/server.key\" \nCreate server.crt and server.key file \nFirst, Generate the server.key using openssl. \ncd ~ \nopenssl genrsa -des3 -out server.key 1024 \nThe above command will ask for the password. Make sure to remember \nthis password. You need this while starting your Apache later. \nIf you don’t provide a password, you’ll get the following error message. \n2415:error:28069065:lib(40):UI_set_result:result too \nsmall:ui_lib.c:849:You must type in 4 to 8191 characters \nNext, generate a certificate request file (server.csr) using the above \nserver.key file. \nopenssl req -new -key server.key -out server.csr \nFinally, generate a self signed ssl certificate (server.crt) using the above \nserver.key and server.csr file. \nopenssl x509 -req -days 365 -in server.csr -signkey \nserver.key -out server.crt \nFor more details refer to: How To Generate SSL Key, CSR and Self Signed \nCertificate For Apache \n194\n"
},
{
"page_number": 195,
"text": "Linux 101 Hacks www.thegeekstuff.com\n Copy the server.key and server.crt \nCopy the server.key and server.crt file to appropriate Apache \nconfiguration directory location. \ncd ~ \ncp server.key /usr/local/apache2/conf/ \ncp server.crt /usr/local/apache2/conf/ \nStart the apache and verify SSL \nStart the Apache as shown below. \n/usr/local/apache2/bin/apachectl start \nThis will prompt you to enter the password for your private key. \nApache/2.2.17 mod_ssl/2.2.17 (Pass Phrase Dialog) \nServer www.example.com:443 (RSA) \nEnter pass phrase: \nOK: Pass Phrase Dialog successful. \nBy default Apache SSL runs on 443 port. Open a web browser and verify \nthat you can access your Apache using https://{your-ip-address} \nAny Questions?\nDiscuss it here: How To Install Apache 2 with SSL on \nLinux (with mod_ssl, openssl)\nAdditional Apache Install Examples:\nHow To Generate SSL Key, CSR and Self Signed Certificate \nFor Apache \n195\n"
},
{
"page_number": 196,
"text": "Linux 101 Hacks www.thegeekstuff.com\n \nInstall Apache 2 from Source on Linux\nHack 76. Install PHP from Source \nAll Linux distributions comes with PHP. However, it is recommended to \ndownload latest PHP source code, compile and install on Linux. This will \nmake it easier to upgrade PHP on an ongoing basis immediately after a \nnew patch or release is available for download from PHP. This hack \nexplains how to install PHP5 from source on Linux. \nPrerequisites \nApache web server should already be installed. Refer to my previous \npost on How to install Apache 2 on Linux. If you are planning to use PHP \nwith MySQL, you should have My SQL already installed.\nDownload PHP \nDownload the latest source code from PHP Download page. Current \nstable release is 5.2.6. Move the source to /usr/local/src and extract is as \nshown below. \n# bzip2 -d php-5.2.6.tar.bz2 \n# tar xvf php-5.2.6.tar \nInstall PHP \nView all configuration options available for PHP using ./configure –-help \n(two hyphen in front of help). The most commonly used option is –-\nprefix={install-dir-name} to install PHP on a user defined directory. \n# cd php-5.2.6 \n# ./configure --help \nIn the following example, PHP will be compiled and installed under the \ndefault location /usr/local/lib with Apache configuration and MySQL \nsupport. \n196\n"
},
{
"page_number": 197,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# ./configure --with-apxs2=/usr/local/apache2/bin/apxs \n--with-mysql \n# make \n# make install \n# cp php.ini-dist /usr/local/lib/php.ini \nConfigure httpd.conf for PHP \nModify the /usr/local/apache2/conf/httpd.conf to add the following: \n \nSetHandler application/x-httpd-php \n \nMake sure the httpd.conf has the following line that will get \nautomatically inserted during the PHP installation process. \nLoadModule php5_module modules/libphp5.so \nRestart the apache as shown below: \n# /usr/local/bin/apache2/apachectl restart \nVerify PHP Installation \nCreate a test.php under /usr/local/apache2/htdocs with the following \ncontent \n# vi test.php \n \nGo to http://local-host/test.php , which will show a detailed information \nabout all the PHP configuration options and PHP modules installed on the \nsystem. \n197\n"
},
{
"page_number": 198,
"text": "Linux 101 Hacks www.thegeekstuff.com\nTrouble shooting during installation \nError 1: configure: error: xml2-config not found: \nWhile performing the ./configure during PHP installation, you may get \nthe following error: \n# ./configure --with-apxs2=/usr/local/apache2/bin/apxs \n--with-mysql \nConfiguring extensions \nchecking whether to enable LIBXML support... yes \nchecking libxml2 install dir... no \nchecking for xml2-config path... \nconfigure: error: xml2-config not found. Please check your \nlibxml2 installation. \nInstall thelibxml2-devel and zlib-devel as shown below to the fix this \nissue. \n# rpm -ivh /home/downloads/linux-iso/libxml2-devel-2.6.26-\n2.1.2.0.1.i386.rpm /home/downloads/linux-iso/zlib-devel-\n1.2.3-3.i386.rpm \nPreparing...##################################### [100%] \n1:zlib-devel##################################### [ 50%] \n2:libxml2-devel################################## [100%] \nError 2: configure: error: Cannot find MySQL header files. \nWhile performing the ./configure during PHP installation, you may get \nthe following error: \n# ./configure --with-apxs2=/usr/local/apache2/bin/apxs \n--with-mysql \nchecking for MySQL UNIX socket location... \n/var/lib/mysql/mysql.sock \nconfigure: error: Cannot find MySQL header files under \nyes. Note that the MySQL client library is not bundled \nanymore! \n198\n"
},
{
"page_number": 199,
"text": "Linux 101 Hacks www.thegeekstuff.com\nInstall the MySQL-devel-community package as shown below to fix this \nissue. \n# rpm -ivh /home/downloads/MySQL-devel-community-5.1.25-\n0.rhel5.i386.rpm \nPreparing...###################################### [100%] \n1:MySQL-devel-community########################### [100%] \nAny Questions?\nDiscuss it here: Instruction Guide to Install PHP5 from \nSource on Linux\nHack 77. Install MySQL \nMost of the Linux distro comes with MySQL. If you want use MySQL, my \nrecommendation is that you download the latest version of MySQL and \ninstall it yourself. Later you can upgrade it to the latest version when it \nbecomes available. This hack explains how to install the latest free \ncommunity edition of MySQL on Linux platform. \nDownload the latest stable release of MySQL \nDownload mySQL from mysql.com . Please download the community \nedition of MySQL for your appropriate Linux platform. I downloaded the \n“Red Hat Enterprise Linux 5 RPM (x86)”. Make sure to download MySQL \nServer, Client and “Headers and libraries” from the download page. \n•\nMySQL-client-community-5.1.25-0.rhel5.i386.rpm \n•\nMySQL-server-community-5.1.25-0.rhel5.i386.rpm \n•\nMySQL-devel-community-5.1.25-0.rhel5.i386.rpm \nIf you want to remove the existing default MySQL that came with the \nLinux distro , do the following.\nDo not perform this on an system where the MySQL database is getting \nused by some application. \n199\n"
},
{
"page_number": 200,
"text": "Linux 101 Hacks www.thegeekstuff.com\n[local-host]# rpm -qa | grep -i mysql \nmysql-5.0.22-2.1.0.1 \nmysqlclient10-3.23.58-4.RHEL4.1 \n[local-host]# rpm -e mysql --nodeps \nwarning: /etc/my.cnf saved as /etc/my.cnf.rpmsave \n[local-host]# rpm -e mysqlclient10 \nInstall the downloaded MySQL package \nInstall the MySQL Server and Client packages as shown below. \n[local-host]# rpm -ivh MySQL-server-community-5.1.25-\n0.rhel5.i386.rpm MySQL-client-community-5.1.25-\n0.rhel5.i386.rpm \nPreparing...####################################### [100%] \n1:MySQL-client-community########################### [ 50%] \n2:MySQL-server-community########################### [100%] \nThis will also display the following output and start the MySQL daemon \nautomatically. \nPLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER! \nTo do so, start the server, then issue the following \ncommands: \n/usr/bin/mysqladmin -u root password 'new-password' \n/usr/bin/mysqladmin -u root -h medica2 password 'new-\npassword' \n \nAlternatively you can run: \n/usr/bin/mysql_secure_installation \n200\n"
},
{
"page_number": 201,
"text": "Linux 101 Hacks www.thegeekstuff.com\nStarting MySQL.[ OK ] \nGiving mysqld 2 seconds to start \nInstall the “Header and Libraries” that are part of the MySQL-devel \npackages. \n[local-host]# rpm -ivh MySQL-devel-community-5.1.25-\n0.rhel5.i386.rpm \nPreparing...####################################### [100%] \n1:MySQL-devel-community ########################## [100%] \nNote: When I was compiling PHP with MySQL option from source on the \nLinux system, it failed with the following error. Installing the MySQL-\ndevel-community package fixed this problem in installing PHP from \nsource. \nconfigure: error: Cannot find MySQL header files under \nyes. \nNote that the MySQL client library is not bundled anymore! \nPerform post-install security activities on MySQL. \nAt a bare minimum you should set a password for the root user as shown \nbelow: \n[local-user]# /usr/bin/mysqladmin -u root password \n'My2Secure$Password' \nThe best option is to run the mysql_secure_installation script that will \ntake care of all the typical security related items on the MySQL as shown \nbelow. On a high level this does the following items: \n•\nChange the root password \n•\nRemove the anonymous user \n•\nDisallow root login from remote machines \n201\n"
},
{
"page_number": 202,
"text": "Linux 101 Hacks www.thegeekstuff.com\n•\nRemove the default sample test database \n[local-host]# /usr/bin/mysql_secure_installation \nNOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR \nALL MySQL SERVERS IN PRODUCTION USE! PLEASE READ EACH \nSTEP CAREFULLY! \nEnter current password for root (enter for none): \nOK, successfully used password, moving on... \nChange the root password? [Y/n] Y \nNew password: \nRe-enter new password: \nPassword updated successfully! \nReloading privilege tables.. ... Success! \nRemove anonymous users? [Y/n] Y \nDisallow root login remotely? [Y/n] Y \nRemove test database and access to it? [Y/n] Y \nReload privilege tables now? [Y/n] Y \ninstallation should now be secure. \nThanks for using MySQL! \nVerify the MySQL installation: \nYou can check the MySQL installed version by performing mysql -V as \nshown below: \n [local-host]# mysql -V \n202\n"
},
{
"page_number": 203,
"text": "Linux 101 Hacks www.thegeekstuff.com\nmysql Ver 14.14 Distrib 5.1.25-rc, for redhat-linux-gnu \n(i686) using readline 5.1 \nConnect to the MySQL database using the root user and make sure the \nconnection is successful. \n[local-host]# mysql -u root -p \nEnter password: \nmysql> \nFollows the steps below to stop and start MySQL \n[local-host]# service mysql status \nMySQL running (12588) [ OK ] \n[local-host]# service mysql stop \nShutting down MySQL. [ OK ] \n[local-host]# service mysql start \nStarting MySQL. [ OK ]\nAny Questions?\nDiscuss it here: Howto Install MySQL on Linux \nAdditional MySQL Install Examples: \nHow to Install MySQL Database Using Yum groupinstall\n203\n"
},
{
"page_number": 204,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 78. Install LAMP Stack\nInstalling LAMP stack using yum is very easy and takes only minutes. \nThis is a good option for beginners who don’t feel comfortable installing \nfrom source. Also, Installing LAMP stack using yum is a good choice, if \nyou want to keep things simple and just use the default configuration. \nInstall Apache using Yum \n# rpm -qa | grep httpd \nIf the above command did not return anything, install apache as shown \nbelow\n# yum install httpd \nVerify that Apache got installed successfully \n# rpm -qa | grep -i http \nhttpd-tools-2.2.9-1.fc9.i386 \nhttpd-2.2.9-1.fc9.i386 \nEnable httpd service to start automatically during system startup using \nchkconfig. Start the Apache as shown below. \n# chkconfig httpd on \n# service httpd start \nStarting httpd: [ OK ] \nInstall MySQL using Yum \nYum is very smart to identify all the dependencies and install those \nautomatically. For example, while installing mysql-server using yum, it \nalso automatically installs the depended mysql-libs, perl-DBI, mysql, \nperl-DBD-MySQL packages as shown below. \n204\n"
},
{
"page_number": 205,
"text": "Linux 101 Hacks www.thegeekstuff.com\n # yum install mysql-server \nPartial output of the above yum install mysql-server command: \nDependencies Resolved \nTransaction Summary \n======================================================== \nInstall 5 Package(s) \nUpdate 0 Package(s) \nRemove 0 Package(s) \nTotal download size: 15 M \nIs this ok [y/N]: y \nRunning Transaction \nInstalling : mysql-libs [1/5] \nInstalling : perl-DBI [2/5] \nInstalling : mysql [3/5] \nInstalling : perl-DBD-MySQL [4/5] \nInstalling : mysql-server [5/5] \nComplete! \nVerify whether MySQL got installed properly. \n# rpm -qa | grep -i mysql \nphp-mysql-5.2.6-2.fc9.i386 \nmysql-libs-5.0.51a-1.fc9.i386 \nmysql-server-5.0.51a-1.fc9.i386 \nperl-DBD-MySQL-4.005-8.fc9.i386 \nmysql-5.0.51a-1.fc9.i386 \n205\n"
},
{
"page_number": 206,
"text": "Linux 101 Hacks www.thegeekstuff.com\n \n# mysql -V \nmysql Ver 14.12 Distrib 5.0.51a, for redhat-linux-gnu \n(i386) using readline 5.0 \nConfigure MySQL to start automatically during system startup. \n# chkconfig mysqld on \nStart MySQL service. \n# service mysqld start \nThe first time when you start mysqld, it will give additional information \nmessage indicating to perform post-install configuration as shown below. \nInitializing MySQL database: \nInstalling MySQL system tables... OK \nFilling help tables... OK \nTo start mysqld at boot time you have to copy \nsupport-files/mysql.server to the right place for your \nsystem \nPLEASE REMEMBER TO SET A PASSWORD FOR MySQL root USER ! \nStart the server, then issue the following commands: \n/usr/bin/mysqladmin -u root password 'new-password' \n/usr/bin/mysqladmin -u root -h dev-db password 'new-\npassword' \nAlternatively you can run: \n/usr/bin/mysql_secure_installation \n206\n"
},
{
"page_number": 207,
"text": "Linux 101 Hacks www.thegeekstuff.com\nStarting MySQL: \n[ OK ] \nPerform MySQL post-installation activities \nAfter the mysql installation, you can login to mysql root account without \nproviding any password as shown below. \n# mysql -u root \nmysql> \nTo fix this problem, you need to assign a password to mysql root account \nas shown below. Execute mysql_secure_installation script, which \nperforms the following activities: \n•\nAssign the root password \n•\nRemove the anonymous user \n•\nDisallow root login from remote machines \n•\nRemove the default sample test database \n# /usr/bin/mysql_secure_installation \nPartial output of mysql_secure_installation script: \nEnter current password for root (enter for none): \nOK, successfully used password, moving on... \nSet root password? [Y/n] Y \nNew password: [Note: Enter the mysql root password here] \nRe-enter new password: \nPassword updated successfully! \nRemove anonymous users? [Y/n] Y \nDisallow root login remotely? [Y/n] Y \nRemove test database and access to it? [Y/n] Y \n207\n"
},
{
"page_number": 208,
"text": "Linux 101 Hacks www.thegeekstuff.com\nReload privilege tables now? [Y/n] Y \n... Success! \nVerify the MySQL post-install activities. Now root access without \npassword is denied.\n# mysql -u root \nERROR 1045 (28000):Access denied for user \n'root'@'localhost'(using password:NO) \nTest database is not available anymore.\n# mysql -u root -p \nEnter password: \nmysql> show databases; \n+--------------------+ \n| Database | \n+--------------------+ \n| information_schema | \n| mysql | \n+--------------------+ \n2 rows in set (0.00 sec) \nInstall PHP using Yum \n# yum install php \nPartial output of yum install php: \nDependencies Resolved \nTransaction Summary \n208\n"
},
{
"page_number": 209,
"text": "Linux 101 Hacks www.thegeekstuff.com\n======================================================== \nInstall 3 Package(s) \nUpdate 0 Package(s) \nRemove 0 Package(s) \nTotal download size: 3.8 M \nIs this ok [y/N]: y \nRunning Transaction \nInstalling : php-common [1/3] \nInstalling : php-cli [2/3] \nInstalling : php [3/3] \nComplete! \nVerify that php got installed successfully. \n# rpm -qa | grep -i php \nphp-cli-5.2.6-2.fc9.i386 \nphp-5.2.6-2.fc9.i386 \nphp-common-5.2.6-2.fc9.i386 \nInstall MySQL module for PHP. \n# yum install php-mysql \nPartial output of yum install php-mysql: \nDependencies Resolved \nTransaction Summary \n==================================================== \nInstall 2 Package(s) \n209\n"
},
{
"page_number": 210,
"text": "Linux 101 Hacks www.thegeekstuff.com\nUpdate 0 Package(s) \nRemove 0 Package(s) \nTotal download size: 143 k \nIs this ok [y/N]: y \nRunning Transaction \nInstalling : php-pdo [1/2] \nInstalling : php-mysql [2/2] \nComplete! \nIf you need additional PHP modules, install them using yum as shown \nbelow. \n# yum install php-common php-mbstring php-mcrypt php-devel \nphp-xml php-gd \nAny Questions?\nDiscuss it here: How To Install Or Upgrade LAMP Using \nYum\nHack 79. Install XAMPP\nTo run various open source applications you might have to install \nApache, MySQL, PHP, and Perl (or some combination of these). For those \nwho have difficulties installing and configuring these separately, XAMPP \nmight be helpful. \nXAMPP is Apache distribution that contains MySQL, PHP and Perl. You \nreally don’t need to worry about configuring MySQL, PHP, or Perl for \nApache. Just install XAMPP, and everything is already pre-built and ready \nto go. It is that easy! \n210\n"
},
{
"page_number": 211,
"text": "Linux 101 Hacks www.thegeekstuff.com\n \nAlso, XAMPP is available for Linux, Windows, Mac OS, and Solaris. \nDownload XAMPP \nDownload XAMPP from xampp in sourceforge. \nInstall XAMPP \nExtract the tar file under /opt directory. \n# cd /opt \n# tar xvzf xampp-linux-1.7.3a.tar.gz \nStart or stop XAMPP \nStart xampp. It starts all the xampp services. \n# /opt/lampp/lampp start \nStop xampp. It stops all the xampp services. \n# /opt/lampp/lampp stop \nStart particular XAMPP service \nStart a particular service by specifying the name of the service along \nwith start. For example, following starts only Apache (along with PHP). \n# /opt/lampp/lampp startapache \nXAMPP: Starting Apache with SSL (and PHP5)... \nNote: Use startmysql in the argument to start only mysql \nStop particular service \nSimilar to start, you can also stop a particular server. For example, \nfollowing stops only MySQL. \n211\n"
},
{
"page_number": 212,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# /opt/lampp/lampp stopmysql \nXAMPP: Stopping MySQL... \nXAMPP Configuration file \nConfiguration files are available under /opt/lampp/etc/. Some of the \nxampp config files are httpd.conf, my.cnf, php.ini. \nAny Questions?\nDiscuss it here: XAMPP: Easy Apache, MySQL, PHP, Perl \nInstall\nHack 80. Secure Your Apache Web Server \nIf you are a sysadmin, you should secure your Apache web server by \nfollowing the tips mentioned in this hack. \nRun Apache as separate user and group \nBy default, apache might run as nobody or daemon. It is good to run \napache in its own non-privileged account. For example: apache. \nCreate apache group and user. \ngroupadd apache \nuseradd -d /usr/local/apache2/htdocs -g apache -s \n/bin/false apache \nModify the httpd.conf, and set User and Group appropriately. \n# vi httpd.conf \nUser apache \nGroup apache \n212\n"
},
{
"page_number": 213,
"text": "Linux 101 Hacks www.thegeekstuff.com\nAfter this, if you restart apache, and do ps -ef, you’ll see that the apache \nis running as “apache” (Except the 1st httpd process, which will always \nrun as root). \n# ps -ef | grep -i http | awk '{print $1}' \nroot \napache \napache \napache \napache \napache \nRestrict access to root directory (Use Allow and Deny) \nSecure the root directory by setting the following in the httpd.conf \n \n Options None \n Order deny,allow \n Deny from all \n \nIn the above: \n•\nOptions None – Set this to None, which will not enable any \noptional extra features. \n•\nOrder deny,allow – This is the order in which the “Deny” and \n“Allow” directives should be processed. This processes the \n“deny” first and “allow” next. \n•\nDeny from all – This denies request from everybody to the root \ndirectory. There is no Allow directive for the root directory. So, \nnobody can access it. \n213\n"
},
{
"page_number": 214,
"text": "Linux 101 Hacks www.thegeekstuff.com\nSet appropriate permissions for conf and bin directory \nbin and conf directory should be viewed only by authorized users. It is \ngood idea to create a group, and add all users who are allowed to \nview/modify the apache configuration files to this group. \nLet us call this group: apacheadmin \nCreate the group. \ngroupadd apacheadmin \nAllow access to bin directory for this group. \nchown -R root:apacheadmin /usr/local/apache2/bin \nchmod -R 770 /usr/local/apache2/bin \nAllow access to conf directory for this group. \nchown -R root:apacheadmin /usr/local/apache2/conf \nchmod -R 770 /usr/local/apache2/conf \nAdd appropriate members to this group. In this example, both ramesh \nand john are part of apacheadmin \n# vi /etc/group \napacheadmin:x:1121:ramesh,john \nDisable Directory Browsing \nIf you don’t do this, users will be able to see all the files (and directories) \nunder your root (or any sub-directory). \nFor example, if they go to http://{your-ip}/images/ and if you don’t have \nan index.html under images, they’ll see all the image files (and the sub-\ndirectories) listed in the browser (just like a ls -1 output). From here, they \n214\n"
},
{
"page_number": 215,
"text": "Linux 101 Hacks www.thegeekstuff.com\ncan click on the individual image file to view it, or click on a sub-\ndirectory to see its content. \nTo disable directory browsing, you can either set the value of Options \ndirective to “None” or “-Indexes”. A – in front of the option name will \nremove it from the current list of options enforced for that directory. \nIndexes will display a list of available files and sub-directories inside a \ndirectory in the browser (only when no index.html is present inside that \nfolder). So, Indexes should not be allowed. \n \n Options None \n Order allow,deny \n Allow from all \n \n(or) \n \n Options -Indexes \n Order allow,deny \n Allow from all \n \nDon’t allow .htaccess \nUsing .htaccess file inside a specific sub-directory under the htdocs (or \nanywhere outside), users can overwrite the default apache directives. \nOn certain situations, this is not good, and should be avoided. You \nshould disable this feature. \nYou should not allow users to use the .htaccess file and override apache \ndirectives. To do this, set “AllowOverride None” in the root directory. \n \n215\n"
},
{
"page_number": 216,
"text": "Linux 101 Hacks www.thegeekstuff.com\n Options None \n AllowOverride None \n Order allow,deny \n Allow from all \n \nAdditional Apache Hardening Examples:\n10 Tips to Secure Your Apache Web Server on UNIX / Linux\nHack 81. Apachectl and Httpd Tips\nAfter you have installed Apache2, if you want to use apachectl and httpd \nto it’s maximum potential, you should go beyond using start, stop and \nrestart. The 9 practical examples provided in this hack will help you to \nuse apachectl and httpd very effectively. \nApachectl acts as SysV init script, taking arguments like start, stop, \nrestart and status. It also acts as front-end to httpd command, by simply \npassing the command line arguments to httpd. So, all the commands \nyou execute using apachectl, can also be executed directly by calling \nhttpd. \nPass different httpd.conf filename to apachectl \nTypically you’ll modify the original httpd.conf to try out different Apache \ndirectives. If something doesn’t work out, you’ll revert back the changes. \nInstead of playing around with the original httpd.conf, copy it to a new \nhttpd.conf.debug and use this new httpd.conf.debug file with Apache for \ntesting purpose as shown below using option -f. \n# apachectl -f conf/httpd.conf.debug \n# httpd -k start -f conf/httpd.conf.debug \n216\n"
},
{
"page_number": 217,
"text": "Linux 101 Hacks www.thegeekstuff.com\n[Note: you can use either apachectl or httpd as shown \nabove] \n# ps -ef | grep http \nroot 25080 1 0 23:26 00:00:00 /usr/sbin/httpd -f \nconf/httpd.conf.debug \napache 25099 25080 0 23:28 00:00:00 /usr/sbin/httpd -f \nconf/httpd.conf.debug \n[Note: ps shows the httpd running with httpd.conf.debug \nfile] \nOnce you are satisfied with the changes and Apache runs without any \nproblem with httpd.conf.debug, you can copy the changes to httpd.conf \nand start the Apache normally as shown below. \n# cp httpd.conf.debug httpd.conf \n# apachectl stop \n# apachectl start \n# ps -ef | grep httpd \nroot 25114 1 0 23:28 00:00:00 /usr/sbin/httpd -k \nstart \ndaemon 25115 25114 0 23:28 00:00:00 /usr/sbin/httpd -k \nstart \n[Note: ps indicates that the httpd is running using the \ndefault config file] \nUse a temporary DocumentRoot without modifying \nhttpd.conf \nThis is very helpful, when you are trying out different layout for your \nwebsite and don’t want to modify the original files under the default \nDocumentRoot. Take a copy of your original DocumentRoot directory \n(/var/www/html) to a new temporary DocumentRoot directory \n(/var/www/html_debug). Make all your changes under this temporary \nDocumentRoot directory (/var/www/html_debug) and start the Apache \nwith this temporary directory as shown below using option -c. \n217\n"
},
{
"page_number": 218,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# httpd -k start -c \"DocumentRoot /var/www/html_debug/\" \nIf you want to go back to original configuration using the default \nDocumentRoot (/var/www/html), simply restart the Apache as shown \nbelow. \n# httpd -k stop \n# apachectl start \nIncrease the LogLevel temporarily \nWhile you are debugging an issue, you can change the LogLevel of the \nApache temporarily, without modifying the LogLevel directive in the \nhttpd.conf as shown below using option -e. In this example, the LogLevel \nis set to debug. \n# httpd -k start -e debug \n[Sun Aug 17 13:53:06 2008] [debug] mod_so.c(246): loaded \nmodule auth_basic_module \n[Sun Aug 17 13:53:06 2008] [debug] mod_so.c(246): loaded \nmodule auth_digest_module \nPossible values you can pass to option -e are: debug, info, notice, warn, \nerror, crit, alert, emerg \nDisplay the modules compiled inside Apache using option \n-l \n# httpd -l \nCompiled in modules: \ncore.c \nprefork.c \nhttp_core.c \nmod_so.c \n218\n"
},
{
"page_number": 219,
"text": "Linux 101 Hacks www.thegeekstuff.com\nDisplay both static and dynamic module loaded by Apache \nWhen you pass option -l, to httpd, it will display only the static modules. \nPassing option -M, will display both static and shared modules as shown \nbelow. \n# httpd -M \nLoaded Modules: \ncore_module (static) \nmpm_prefork_module (static) \nhttp_module (static) \nso_module (static) \nauth_basic_module (shared) \nauth_digest_module (shared) \nauthn_file_module (shared) \nauthn_alias_module (shared) \nSyntax OK \nShow all accepted directives inside httpd.conf \nThis is like an extended help for httpd, which will display all the \nhttpd.conf directives and the places where they are valid. For a specific \ndirective, it tells all the possible values and where it can be used inside \nthe httpd.conf. This can be very helpful, when you want to quickly know \nabout a particular Apache directive. \n# httpd -L \nHostnameLookups (core.c) \n\"on\" to enable, \"off\" to disable reverse DNS lookups, or \n\"double\" to enable double-reverse DNS lookups \nAllowed in *.conf anywhere \nServerLimit (prefork.c) \nMaximum value of MaxClients for this run of Apache \nAllowed in *.conf only outside , or \n \n219\n"
},
{
"page_number": 220,
"text": "Linux 101 Hacks www.thegeekstuff.com\nKeepAlive (http_core.c) \nWhether persistent connections should be On or Off \nAllowed in *.conf only outside , or \n \nLoadModule (mod_so.c) \na module name and the name of a shared object file to load \nit from \nAllowed in *.conf only outside , or \n \nValidate the httpd.conf after making changes \nUse option -t to validate whether there are any issues with a specific \nApache configuration file. In the example shown below, it displays that \nthere is a problem at line 148 in the httpd.conf.debug. \nmod_auth_basicso is missing a . (period) before the so. \n# httpd -t -f conf/httpd.conf.debug \nhttpd: Syntax error on line 148 of \n/etc/httpd/conf/httpd.conf.debug: \nCannot load /etc/httpd/modules/mod_auth_basicso into \nserver: \n/etc/httpd/modules/mod_auth_basicso: cannot open shared \nobject file: No such file or directory \nOnce you fix the issue, it will display Syntax OK. \n# httpd -t -f conf/httpd.conf.debug \nSyntax OK \nDisplay the httpd build parameters \nUse option -V (upper-case V), to display Apache version number and all \nthe parameters that are used while building the Apache. \n# httpd -V \nServer version: Apache/2.2.9 (Unix) \n220\n"
},
{
"page_number": 221,
"text": "Linux 101 Hacks www.thegeekstuff.com\nServer built: Jul 14 2008 15:36:56 \nServer's Module Magic Number: 20051115:15 \nServer loaded: APR 1.2.12, APR-Util 1.2.12 \nCompiled using: APR 1.2.12, APR-Util 1.2.12 \nArchitecture: 32-bit \nServer MPM: Prefork \nthreaded: no \nforked: yes (variable process count) \nServer compiled with.... \n-D APACHE_MPM_DIR=\"server/mpm/prefork\" \n-D APR_HAS_SENDFILE \n-D HTTPD_ROOT=\"/etc/httpd\" \n-D SUEXEC_BIN=\"/usr/sbin/suexec\" \n-D DEFAULT_PIDLOG=\"logs/httpd.pid\" \n-D DEFAULT_SCOREBOARD=\"logs/apache_runtime_status\" \n-D DEFAULT_LOCKFILE=\"logs/accept.lock\" \n-D DEFAULT_ERRORLOG=\"logs/error_log\" \n-D AP_TYPES_CONFIG_FILE=\"conf/mime.types\" \n-D SERVER_CONFIG_FILE=\"conf/httpd.conf\" \n...\nIf you want display only the Apache version number, use the option -v \n(lower-case v) as shown below. \n# httpd -v \nServer version: Apache/2.2.9 (Unix) \nServer built: Jul 14 2008 15:36:56 \nLoad a specific module only on demand. \nSometimes you may not want to load all the modules in the Apache. For \ne.g. You may want to load ldap related modules to Apache, only when \nyou are testing LDAP. This can be achieved as shown below. \n221\n"
},
{
"page_number": 222,
"text": "Linux 101 Hacks www.thegeekstuff.com\nModify the httpd.conf and add IfDefine directive called load-ldap (you \ncan name this anything you want). \n \nLoadModule ldap_module modules/mod_ldap.so \nLoadModule authnz_ldap_module modules/mod_authnz_ldap.so \n \nWhen you are testing ldap and would like to Load the ldap related \nmodules, pass the load-ldap to Option -D, as shown below: \n# httpd -k start -e debug -Dload-ldap -f \n/etc/httpd/conf/httpd.conf.debug \n[Sun Aug 17 14:14:58 2008] [debug] mod_so.c(246): loaded \nmodule ldap_module \n[Sun Aug 17 14:14:58 2008] [debug] mod_so.c(246): loaded \nmodule authnz_ldap_module \n[Note: Pass -Dload-ldap, to load the ldap modules into \nApache] \n# apachectl start \n[Note: Start the Apache normally, if you don't want to \nload the ldap modules.] \nAny Questions?\nDiscuss it here: 9 Tips to Use Apachectl and Httpd like \na Power User\n222\n"
},
{
"page_number": 223,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHack 82. Setup Apache Virtual Host \nConfiguration\nUncomment httpd-vhosts.conf in httpd.conf \nIf you’ve installed Apache 2 from source, by default, the following line \nwill be commented in the httpd.conf file. Uncomment this line. \n# vi /usr/local/apache2/conf/httpd.conf \nInclude conf/extra/httpd-vhosts.conf \nSetup virtual hosts \nModify the httpd-vhosts.conf as shown below to setup named-based \nvirtual host setting for two hosts. \n•\nNameVirtualHost *:80 – Indicates that all the name-based virtual \nhosts will be listening on the default port 80 \n•\n – Enclose all the apache \nconfiguration parameters for each and every virtual host \nbetween these VirtualHost tags. Any apache directives can be \nused within the virtualhost container. \n•\nIn the following example, we are setting up virtual host for \nthegeekstuff.com and top5freeware.com listening on the same \nport 80. So, there will be two , \none for each website. \n•\nWhen you go to thegeekstuff.com, the files under \n/usr/local/apache2/docs/thegeekstuff will be served by Apache; \nand the access_log and error_log for this site will go under \n/usr/local/apache2/logs/thegeekstuff \n# vi /usr/local/apache2/conf/extra/httpd-vhosts.conf \nNameVirtualHost *:80 \n \n \n ServerAdmin ramesh@thegeekstuff.com \n DocumentRoot \"/usr/local/apache2/docs/thegeekstuff\" \n ServerName thegeekstuff.com \n223\n"
},
{
"page_number": 224,
"text": "Linux 101 Hacks www.thegeekstuff.com\n ServerAlias www.thegeekstuff.com \n ErrorLog \"logs/thegeekstuff/error_log\" \n CustomLog \"logs/thegeekstuff/access_log\" common \n \n \n ServerAdmin ramesh@top5freeware.com \n DocumentRoot \"/usr/local/apache2/docs/top5freeware\" \n ServerName top5freeware.com \n ServerAlias www.top5freeware.com \n ErrorLog \"logs/top5freeware/error_log\" \n CustomLog \"logs/top5freeware/access_log\" common \n \nCheck VirtualHost Configuration Syntax \nVerify virtual configuration syntax using “httpd -S” as shown below. \nWhen everything is setup properly, it just displays “Syntax OK”. \n# /usr/local/apache2/bin/httpd -S \nVirtualHost configuration: \nSyntax OK \nWhen something is not configured properly, it will display warning \nmessage, including “directory does not exit” message as shown below. \n# /usr/local/apache2/bin/httpd -S \nWarning: DocumentRoot \n[/usr/local/apache2/docs/top5freeware] does not exist \nWarning: ErrorLog [/usr/local/apache2/logs/thegeekstuff] \ndoes not exist \nSyntax OK \n224\n"
},
{
"page_number": 225,
"text": "Linux 101 Hacks www.thegeekstuff.com\nRestart the Apache and test \n# /usr/local/apache2/bin/apachectl restart \nNow, when you go to thegeekstuff.com (or www.thegeekstuff.com), the \napache will serve the files from /usr/local/apache2/docs/thegeekstuff \ndirectory. \nWhen you go to top5freeware.com (or www.top5freeware.com), the \nsame apache running on the same server will serve the files from \n/usr/local/apache2/docs/top5freeware directory. \nJust to reiterate, for the name-based virtual host to work properly, the \nDNS entry for both these websites should be pointing to the same \nexternal ip-address of the physical server where the Apache webserver \nis running. \nAny Questions?\nDiscuss it here: How To Setup Apache Virtual Host \nConfiguration (With Examples)\nHack 83. Rotate Apache Logs Files\nThis hack explains how to rotate the apache access_log and error_log \nfiles. \nAdd the following file to /etc/logrotate.d directory. \n# vi /etc/logrotate.d/apache \n/usr/local/apache2/logs/access_log \n/usr/local/apache2/logs/error_log { \n size 100M \n compress \n225\n"
},
{
"page_number": 226,
"text": "Linux 101 Hacks www.thegeekstuff.com\n dateext \n maxage 30 \n postrotate \n /usr/bin/killall -HUP httpd \n ls -ltr /usr/local/apache2/logs | mail -s \n\"$HOSTNAME: Apache restarted and log files rotated\" \nramesh@thegeekstuff.com \n endscript \n} \nNote: Refer to our logrotate tutorial (with 15 examples) that explains \nmore details about how to use logrotate options. \nIn the above /etc/logrotate.d/apache example: \n•\nsize 100M – Once the access_log, and error_log reaches 100M, it \nwill be rotated. You can also use 100k (for Kb), 100G (for GB). \nInstead of size, you can also rotate apache logs using frequency \n(daily, weekly, monthly). \n•\ncompress – Indicates that the rotated log file will be compressed. \nBy default this uses gzip. So, the rotated file will have .gz \nextension. \n•\ndateext - Appends the date in YYYYMMDD format to the rotated \nlog files. i.e Instead of access_log.1.gz, it creates access_log-\n20110616.gz \n•\nmaxage - Indicates how long the rotated log files should be kept. \nIn this example, it will be kept for 30 days. \n•\npostrotate and endscript – Any commands enclosed between \nthese two parameter will be executed after the log is rotated. \nImportant: Once you rotate the log files, you want apache to write the \nnew log messages to the newly created access_log and error_log. So, \nyou need to send the HUP signal to the apache as shown here. Make \nsure to do /usr/bin/killall -HUP httpd, which will restart the apache after \nrotating the log files (Read more about kill). \n226\n"
},
{
"page_number": 227,
"text": "Linux 101 Hacks www.thegeekstuff.com\nAlso, you might want to send an email to yourself indicating that the log \nfile is rotated, along with the output of ls -ltr command as the body of \nthe email. i.e Add the following between “postrotate” and “endscript” \noption (after the killall command). \nls -ltr /usr/local/apache2/logs | mail -s \"$HOSTNAME: \nApache restarted and log files rotated\" \nramesh@thegeekstuff.com \nThe /etc/cron.daily/logrotate script runs everyday that will perform log \nrotate of all the files as specified in the /etc/logrotate.conf and all the file \nunder /etc/logrotate.d directory. \nAfter adding the above /etc/logrotate.d/apache file, for testing purpose, \nyou can manually call the logrotate script as shown below. \n# /etc/cron.daily/logrotate \nOnce the log files are rotated, do a ls to verify them. As we explained \nabove, the rotated log files will be kept for 30 days. \n# ls /usr/local/apache2/logs \naccess_log \nerror_log \naccess_log-20110716.gz \nerror_log-20110716.gz\nAny Questions?\nDiscuss it here: How to Rotate Apache Log Files in Linux\nAdditional Logrotate Examples:\nThe Ultimate Logrotate Command Tutorial with 10 Examples\n227\n"
},
{
"page_number": 228,
"text": "Linux 101 Hacks www.thegeekstuff.com\nChapter 11: Bash Scripting\nHack 84. Execution Sequence of .bash_* files\nThis hack explains the sequence in which the following files are \nexecuted: \n•\n/etc/profile \n•\n~/.bash_profile \n•\n~/.bashrc \n•\n~/.bash_login \n•\n~/.profile \n•\n~/.bash_logout \nExecution sequence for interactive login shell \nFollowing pseudo code explains the sequence of execution of these files. \nexecute /etc/profile \nIF ~/.bash_profile exists THEN \n execute ~/.bash_profile \nELSE \n IF ~/.bash_login exist THEN \n execute ~/.bash_login \n ELSE \n IF ~/.profile exist THEN \n execute ~/.profile \n END IF \n END IF \nEND IF \nWhen you logout of the interactive shell, following is the sequence of \nexecution: \n228\n"
},
{
"page_number": 229,
"text": "Linux 101 Hacks www.thegeekstuff.com\n IF ~/.bash_logout exists THEN \n execute ~/.bash_logout \nEND IF \nPlease note that /etc/bashrc is executed by ~/.bashrc as shown below: \n# cat ~/.bashrc \nif [ -f /etc/bashrc ]; then \n. /etc/bashrc \nfi \nExecution sequence for interactive non-login shell \nWhile launching a non-login interactive shell, following is the sequence \nof execution: \nIF ~/.bashrc exists THEN \n execute ~/.bashrc \nEND IF \nNote: When a non-interactive shell starts up, it looks for ENV \nenvironment variable, and execute the file-name value mentioned in the \nENV variable. \nTest the sequence of execution \nOne of the ways to test the sequence of execution is by adding different \nPS1 values to these files and re-login to the shell and see which PS1 \nvalue got picked up by the Linux prompt. Also, earlier we discussed \nabout how to use PS1 to make your Linux prompt both functional and \nstylish. \n1. /etc/profile gets executed. Add following PS1 line to /etc/profile and re-\nlogin to make sure the Linux prompt changes to the PS1 value set inside \nthe /etc/profile. \n229\n"
},
{
"page_number": 230,
"text": "Linux 101 Hacks www.thegeekstuff.com\n# grep PS1 /etc/profile \nPS1=\"/etc/profile> \" \n[Note: re-login to see the prompt change as shown below] \nLast login: Sat Sep 27 16:43:57 2008 from 192.168.1.2 \n/etc/profile> \nPlease make sure ~/.bash_profile doesn’t have any PS1 for the above to \nwork properly. \n2. ~/.bash_profile gets executed: Add following PS1 to ~/.bash_profile, \n~/.bash_login, ~/.profile and ~/.bashrc. Re-login to make sure the Linux \nprompt changes to the PS1 value set inside the ~/.bash_profile as \nshown below. \n/etc/profile> grep PS1 ~/.bash_profile \nexport PS1=\"~/.bash_profile> \" \n/etc/profile> grep PS1 ~/.bash_login \nexport PS1=\"~/.bash_login> \" \n/etc/profile> grep PS1 ~/.profile \nexport PS1=\"~/.profile> \" \n/etc/profile> grep PS1 ~/.bashrc \nexport PS1=\"~/.bashrc> \" \n[Note: Upon re-login, it executed /etc/profile first and \n~/.bash_profile next. So, it took the PS1 from \n~/.bash_profile as shown below. It also did not execute \n~/.bash_login, as ~/.bash_profile exists] \nLast login: Sat Sep 27 16:48:11 2008 from 192.168.1.2 \n~/.bash_profile> \n230\n"
},
{
"page_number": 231,
"text": "Linux 101 Hacks www.thegeekstuff.com\n3. ~/.bash_login gets executed. Rename the .bash_profile to something \nelse. Re-login to make sure the Linux prompt changes to the PS1 value \nset inside the ~/.bash_login as shown below. \n~/.bash_profile> mv .bash_profile bash_profile_not_used \n[Note: Upon re-login, it executed /etc/profile first. \nSince it cannot find ~/.bash_profile, it executed \n~/.bash_login] \nLast login: Sat Sep 27 16:50:55 2008 from 192.168.1.2 \n~/bash_login> \n4. ~/.profile gets executed. Rename the .bash_login to something else. \nRe-login to make sure the Linux prompt changes to the PS1 value set \ninside the ~/.profile as shown below. \n~/.bash_login> mv .bash_login bash_login_not_used \n[Note: Upon re-login, it executed /etc/profile first. \nSince it cannot find ~/.bash_profile and ~/.bash_login, it \nexecuted ~/.profile] \nLast login: Sat Sep 27 16:56:36 2008 from 192.168.1.2 \n~/.profile> \n5. ~/.bashrc gets executed for non-login shell testing. Executing “bash” \nat the command prompt will give another non-login shell, which will \ninvoke .bashrc as shown below. \n~/.profile> bash \n[Note: This displays PS1 from .bashrc as shown below.] \n~/.bashrc> exit \n[Note: After exiting from non-login shell, we are back to \nlogin shell] \n231\n"
},
{
"page_number": 232,
"text": "Linux 101 Hacks www.thegeekstuff.com\n~/.profile>\nAny Questions?\nDiscuss it here: Execution sequence for \n.bash_profile, .bashrc, .bash_login, .profile and \n.bash_logout\nHack 85. Bash FOR Loops Using C Like Syntax \nThe second form of bash for loop is similar to the ‘C’ programming \nlanguage for loop, which has three expressions (initialization, condition \nand update). \nfor (( expr1; expr2; expr3 )) \ndo \ncommands \ndone \n•\nBefore the first iteration, expr1 is evaluated. This is usually used \nto initialize variables for the loop. \n•\nAll the statements between do and done are executed repeatedly \nas long as the value of expr2 is TRUE. \n•\nAfter each loop iteration, expr3 is evaluated. This is usually used \nto increment a loop counter. \nThe following examples show how to use this syntax in the bash for loop. \nLoop using C-Style \nGenerate and display 5 random numbers using the bash C-style for loop: \n$ cat for10.sh \nfor (( i=1; i <= 3; i++ )) \ndo \n232\n"
},
{
"page_number": 233,
"text": "Linux 101 Hacks www.thegeekstuff.com\necho \"Random number $i: $RANDOM\" \ndone \n$ ./for10.sh \nRandom number 1: 23320 \nRandom number 2: 5070 \nRandom number 3: 15202 \nInfinite Loop Using Bash For \nWhen you don't provide the start, condition, and increment in a C-style \nfor loop, it will execute forever. You need to press Ctrl-C to stop the loop. \n$ cat for11.sh \ni=1; \nfor (( ; ; )) \ndo \nsleep $i \necho \"Number: $((i++))\" \ndone \nNote: Don’t forget you will need to press Ctrl-C to break from this \nexample: \n$ ./for11.sh \nNumber: 1 \nNumber: 2 \nNumber: 3 \nIncrement Two Values Using Comma in C-style for loop \nIn the bash c-style loop, in addition to incrementing the value that is \nused in the condition, you can also increment some other value or \nperform some other action. In both the initialization section and the \nincrement section of the C-style for loop, you can use multiple \nstatements separated with a comma. This example uses i for control and \nmanipulates j separately: \n233\n"
},
{
"page_number": 234,
"text": "Linux 101 Hacks www.thegeekstuff.com\n$ cat for12.sh \nfor ((i=1, j=10; i <= 5 ; i++, j=j+5)) \ndo \necho \"Number $i: $j\" \ndone \n$ ./for12.sh \nNumber 1: 10 \nNumber 2: 15 \nNumber 3: 20 \nNumber 4: 25 \nNumber 5: 30 \nAdditional Bash For Loop Examples:\n12 Bash For Loop Examples for Your Linux Shell Scripting\nHack 86. Debug a Shell Script\nTo debug a shell script use set –xv inside the shell script at the top. \nShell script with no debug command: \n$ cat filesize.sh \n#!/bin/bash \nfor filesize in $(ls -l . | grep \"^-\" | awk '{print $5}') \ndo \n let totalsize=$totalsize+$filesize \ndone \necho \"Total file size in current directory: $totalsize\" \n234\n"
},
{
"page_number": 235,
"text": "Linux 101 Hacks www.thegeekstuff.com\nOutput of Shell script with no debug command: \n$ ./filesize.sh \nTotal file size in current directory: 652 \nShell script with Debug command inside: \nAdd set –xv inside the shell script now to debug the output as shown \nbelow. \n$ cat filesize.sh \n#!/bin/bash \nset -xv \nfor filesize in $(ls -l . | grep \"^-\" | awk '{print $5}') \ndo \n let totalsize=$totalsize+$filesize \ndone \necho \"Total file size in current directory: $totalsize\" \nOutput of Shell script with Debug command inside: \n$ ./fs.sh \n++ ls -l . \n++ grep '^-' \n++ awk '{print $5}' \n+ for filesize in '$(ls -l . | grep \"^-\" | awk '\\''{print \n$5}'\\'')' \n+ let totalsize=+178 \n+ for filesize in '$(ls -l . | grep \"^-\" | awk '\\''{print \n$5}'\\'')' \n+ let totalsize=178+285 \n+ for filesize in '$(ls -l . | grep \"^-\" | awk '\\''{print \n$5}'\\'')' \n+ let totalsize=463+189 \n+ echo 'Total file size in current directory: 652' \n235\n"
},
{
"page_number": 236,
"text": "Linux 101 Hacks www.thegeekstuff.com\nTotal file size in current directory: 652 \nExecute Shell script with debug option: \nInstead of giving the set –xv inside the shell script, you can also provide \nthat while executing the shell script as shown below. \n$ bash -xv filesize.sh \nHack 87. Quoting\necho statement without any special character. \n$ echo The Geek Stuff \nThe Geek Stuff \nEcho statement with a special character ; . semi-colon is a command \nterminator in bash. In the following example, “The Geek” works for the \necho and “Stuff” is treated as a separate Linux command and gives \ncommand not found. \n$ echo The Geek; Stuff \nThe Geek \n-bash: Stuff: command not found \nTo avoid this you can add a \\ in front of semi-colon, which will remove \nthe special meaning of semi-colon and just print it as shown below. \n$ echo The Geek\\; Stuff \nThe Geek; Stuff \nSingle Quote \nUse single quote when you want to literally print everything inside the \nsingle quote. Even the special variables such as $HOSTNAME will be \nprint as $HOSTNAME instead of printing the name of the Linux host. \n236\n"
},
{
"page_number": 237,
"text": "Linux 101 Hacks www.thegeekstuff.com\n$ echo 'Hostname=$HOSTNAME ; Current User=`whoami` ; \nMessage=\\$ is USD' \nHostname=$HOSTNAME ; Current User=`whoami` ; Message=\\$ \nis USD \nDouble Quote \nUse double quotes when you want to display the real meaning of special \nvariables. \n$ echo \"Hostname=$HOSTNAME ; Current User=`whoami` ; \nMessage=\\$ is USD\" \nHostname=dev-db ; Current User=ramesh ; Message=$ is USD \nDouble quotes will remove the special meaning of all characters except \nthe following: \n•\n$ Parameter Substitution. \n•\n` Backquotes \n•\n\\$ Literal Dollar Sign. \n•\n\\´ Literal Backquote. \n•\n\\\" Embedded Doublequote. \n•\n\\\\ Embedded Backslashes. \nHack 88. Read Data File Fields Inside a Shell \nScript \nThis example shows how to read a particular field from a data-file and \nmanipulate it inside a shell-script. For example, let us assume the \nemployees.txt file is in the format of {employee-name}:{employee-id}:\n{department-name}, with colon delimited file as shown below. \n$ cat employees.txt \nEmma Thomas:100:Marketing \n237\n"
},
{
"page_number": 238,
"text": "Linux 101 Hacks www.thegeekstuff.com\nAlex Jason:200:Sales \nMadison Randy:300:Product Development \nSanjay Gupta:400:Support \nNisha Singh:500:Sales \nThe following shell script explains how to read specific fields from this \nemployee.txt file. \n$ vi read-employees.sh \n#!/bin/bash \nIFS=: \necho \"Employee Names:\" \necho \"---------------\" \nwhile read name empid dept \ndo \n echo \"$name is part of $dept department\" \ndone < ~/employees.txt \nAssign execute privilege to the shell script and execute it. \n$ chmod u+x read-employees.sh \n$ ./read-employees.sh \nEmployee Names: \n--------------- \nEmma Thomas is part of Marketing department \nAlex Jason is part of Sales department \nMadison Randy is part of Product Development department \nSanjay Gupta is part of Support department \nNisha Singh is part of Sales department\n238\n"
},
{
"page_number": 239,
"text": "Linux 101 Hacks www.thegeekstuff.com\nChapter 12: System Monitoring and \nPerformance\nHack 89. Free Command\nfree command displays all the necessary information about system \nphysical (RAM) and swap memory. \nSyntax: free [options] \nWhat is the total RAM on my system? \nIn the example below, the total physical memory on this system is 1GB. \nThe values displayed below are in KB. \n# free \n total used free shared buffers cached \nMem: 1034624 1006696 27928 0 174136 615892 \n-/+ buffers/cache: 216668 817956 \nSwap:2031608 0 2031608 \nWhat is the total memory on my system including RAM \nand Swap? \nIn the following command: \n•\noption m displays the values in MB \n•\noption t displays the “Total” line, which is sum of physical and \nswap memory values \n•\noption o is to hide the buffers/cache line from the above \nexample. \n# free –mto \n total used free shared buffers cached \nMem: 1010 983 27 0 170 601 \n239\n"
},
{
"page_number": 240,
"text": "Linux 101 Hacks www.thegeekstuff.com\nSwap: 1983 0 1983 \nTotal: 2994 983 2011 \nHack 90. Top Command \ntop command displays real time information about various performance \nmetrics of the system such as CPU Load, Memory Usage, Processes list \netc. \nSyntax: top [options] \nHow to view my current system status including CPU \nusage? \nExecute top without any option from the command line, which will \ndisplay the output shown below. The top command output will keep \ndisplaying the real-time values, until you press “Control + c” or q to exit \nfrom the command output. \n# top \ntop - 13:10:13 up 171 days, 20:21, 3 users, load \naverage: 0.01, 0.05, 0.00 \nTasks: 194 total, 1 running, 193 sleeping, 0 stopped, \n0 zombie \nCpu(s): 0.6% us, 0.7% sy, 0.0% ni, 98.7% id, 0.0% wa, \n0.0% hi, 0.0% si \nMem: 1034624k total, 1007420k used, 27204k free, \n174540k buffers \nSwap: 2031608k total, 0k used, 2031608k \nfree, 615904k cached \nPID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ \nCOMMAND \n11912 apache 15 0 31828 13m 3916 S 1 \n0.2 0:46.35 httpd \n240\n"
},
{
"page_number": 241,
"text": "Linux 101 Hacks www.thegeekstuff.com\n19299 oracle 19 0 279m 18m 17m S 1 \n0.2 0:00.03 oracle \n11398 jsmith 16 0 107m 28m 6404 S 0 \n0.4 0:03.07 perl \nHow to read the output of the top command shown above? \n•\nLine 1 “top”, indicates that the system has been up and running \nfor 171 days. \n•\nLine 2 “Tasks”, displays the total number of processes along with \na breakdown of running, sleeping, stopped and zombie processes \ncount. \n•\nLine 3 “Cpu(s)” displays the current CPU utilization of the system. \nIn this example, CPU is 98.7% idle \n•\nLine 4 “Mem” and line 5 “Swap” provides the memory \ninformation. This is the same information from the free \ncommand. \n•\nThe rest of the lines display all the active processes on the \nsystem, sorted default by CPU usage (%CPU column). i.e the \nmost CPU intensive processes will be displayed on the top by \ndefault. \nThere are several command line options and interactive options \navailable for top commands. Let us review couple of essential options for \ntop command. \nHow to identify the most memory intensive processes? \nWhile the output of the top command displayed, press F, which will \ndisplay the following message and show all fields available for sorting, \npress n (which is for sorting the processes by Memory) and press enter. \nThis will display the processes in the top output sorted by memory \nusage. \nCurrent Sort Field: K for window 1:Def \nSelect sort field via field letter, type any other key to return \n241\n"
},
{
"page_number": 242,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHow to add additional fields (for e.g. CPU Time) to the top \noutput? \nWhile the top command is running, press f, which will display the \nfollowing message and show all fields available for display, press l, \nwhich will add the CPU Time to the display columns in the top output. \nCurrent Fields: AEHIOQTWKNMbcdfgjplrsuvyzX for window \n1:Def \nToggle fields via field letter, type any other key to return \nHow to get the full path name and parameters of the \nrunning processes? \nWhile the top command is running, press c, which will display full \npathname of running processes as shown below in the command \ncolumn. i.e Instead of httpd, it displays /usr/local/apache2/bin/httpd. \nPID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ \nCOMMAND \n11912 apache 15 0 31828 13m 3916 S 1 \n0.2 0:46.35 /usr/local/apache2/bin/httpd \nHow to view the individual CPUs in the top command? \nWhile the top command is running, press 1 (number one), which will \ndisplay the performance data of the individual CPUs on that machine as \nshown below. \ntop - 13:10:13 up 171 days, 20:21, 3 users, load \naverage: 0.01, 0.05, 0.00 \nTasks: 194 total, 1 running, 193 sleeping, 0 stopped, \n0 zombie \nCpu0 : 10.2% us, 2.6% sy, 0.0% ni, 86.8% id, 0.3% wa, \n0.0% hi, 0.0% si \nCpu1 : 9.6% us, 8.0% sy, 0.0% ni, 82.4% id, 0.0% wa, \n0.0% hi, 0.0% si \nCpu2 : 1.3% us, 1.3% sy, 0.0% ni, 95.0% id, 2.3% wa, \n0.0% hi, 0.0% si \n242\n"
},
{
"page_number": 243,
"text": "Linux 101 Hacks www.thegeekstuff.com\nCpu3 : 0.0% us, 0.0% sy, 0.0% ni, 100.0% id, 0.0% wa, \n0.0% hi, 0.0% si \nMem: 1034624k total, 1007420k used, 27204k free, \n174540k buffers \nSwap: 2031608k total, 0k used, 2031608k \nfree, 615904k cached\nAdditional Top Command Examples: \n15 Practical Linux Top Command Examples\nTop on Steroids – 15 Practical Linux HTOP Examples\nHow To Capture Unix Top Command Output to a File in \nReadable Format\nIFTOP Guide: Display Network Interface Bandwidth Usage \non Linux\nHack 91. Df Command \ndf command (disk free) displays the amount of total and free disk space \navailable on the mounted filesystems. \nSyntax: df [options] [name] \nHow much GB of disk space is free on my system? \nUse df -h as shown below. Option -h displays the values in human \nreadable format (for example: K for Kb, M for Mb and G for Gb). In the \nsample output below, / filesystem has 17GB of disk space available \nand /home/user filesystem has 70GB available. \n# df –h \nFilesystem Size Used Avail Use% Mounted on \n243\n"
},
{
"page_number": 244,
"text": "Linux 101 Hacks www.thegeekstuff.com\n/dev/sda1 64G 44G 17G 73% / \n/dev/sdb1 137G 67G 70G 49% /home/user \n What type of filesystem do I have on my system? \nOption -T will display the information about the filesystem Type. In this \nexample / and /home/user filesystems are ext2. Option -a will display all \nthe filesystems, including the 0 size special filesystem used by the \nsystem. \n# df -Tha \nFilesystem Type Size Used Avail Use% Mounted on \n/dev/sda1 ext2 64G 44G 17G 73% / \n/dev/sdb1 ext2 137G 67G 70G 49% /home/user \nnone proc 0 0 0 - /proc \nnone sysfs 0 0 0 - /sys \nnone devpts 0 0 0 - /dev/pts \nnone tmpfs 2.0G 0 2.0G 0% /dev/shm \nHack 92. Du Command \ndu command (disk usage) will print the file space usage for a particular \ndirectory and its subdirectories. \nHow much space is taken by my home directory and all its \nsubdirectories? \nIn the following example, option -s stands for summary only. i.e it \ndisplays only the total size of /home/jsmith and not the individual sizes \nof all the subdirectories inside the /home/jsmith. Option -h displays the \ninformation in a human readable format. i.e K for KB, M for MB and G for \nGB. The ~ indicates the user home directory. This command is same as \n“du -sh /home/jsmith” \n# du -sh ~ \n320M /home/jsmith \n244\n"
},
{
"page_number": 245,
"text": "Linux 101 Hacks www.thegeekstuff.com\nTo get the subdirectories under /home/jsmith listed, execute the above \ncommand without the s option. \nHack 93. Lsof Commands \nLsof stands for ls open files, which will list all the open files in the \nsystem. The open files include network connection, devices and \ndirectories. The output of the lsof command will have the following \ncolumns: \n•\nCOMMAND process name. \n•\nPID process ID \n•\nUSER Username \n•\nFD file descriptor \n•\nTYPE node type of the file \n•\nDEVICE device number \n•\nSIZE file size \n•\nNODE node number \n•\nNAME full path of the file name. \nView all open files of the system \nExecute the lsof command without any parameter as shown below. \n# lsof | more \nCOMMAND PID USER FD TYPE DEVICE SIZE NODE NAME \ninit 1 root cwd DIR 8,1 4096 2 / \ninit 1 root rtd DIR 8,1 4096 2 / \ninit 1 root txt REG 8,1 32684 983101 \n/sbin/init \ninit 1 root mem REG 8,1 106397 166798 \n/lib/ld-2.3.4.so \ninit 1 root mem REG 8,1 1454802 166799 \n/lib/tls/libc-2.3.4.so \n245\n"
},
{
"page_number": 246,
"text": "Linux 101 Hacks www.thegeekstuff.com\ninit 1 root mem REG 8,1 53736 163964 \n/lib/libsepol.so.1 \ninit 1 root mem REG 8,1 56328 166811 \n/lib/libselinux.so.1 \nskipped… \n \nThe lsof command by itself without may return lot of records as output, \nwhich may not be very meaningful except to give you a rough idea \nabout how many files are open in the system at any given point of view \nas shown below. \n# lsof | wc -l \n3093 \nView open files by a specific user \nUse lsof –u option to display all the files opened by a specific user. \n# lsof –u ramesh \nvi 7190 ramesh txt REG 8,1 474608 \n475196 /bin/vi \nsshd 7163 ramesh 3u IPv6 15088263 \nTCP dev-db:ssh->abc-12-12-12-12.socal.res.rr.com:2631 \n(ESTABLISHED) \nA system administrator can use this command to get some idea on what \nusers are executing on the system. \nList Users of a particular file \nIf you like to view all the users who are using a particular file, use lsof as \nshown below. In this example, it displays all users who are currently \nusing vi. \n# lsof /bin/vi \nCOMMAND PID USER FD TYPE DEVICE SIZE NODE NAME \nvi 7258 root txt REG 8,1 474608 475196 /bin/vi \n246\n"
},
{
"page_number": 247,
"text": "Linux 101 Hacks www.thegeekstuff.com\nvi 7300 ramesh txt REG 8,1 474608 475196 /bin/vi \nHack 94. Vmstat Command \nFor a typical performance monitoring all you need is only vmstat \ncommand. This display memory, swap, IO, system and cpu performance \ninformation. \nThe following command executes vmstat every 1 second for 100 times. \n# vmstat 1 100 \nprocs -----------memory---------- ---swap-- -----io---- \n--system-- ----cpu---- \n r b swpd free buff cache si so bi bo \nin cs us sy id wa \n 0 0 0 282120 134108 5797012 0 0 0 2 \n0 0 0 0 100 0 \n 0 0 0 282120 134108 5797012 0 0 0 0 \n1007 359 0 0 100 0 \n 0 0 0 282120 134108 5797012 0 0 0 0 \n1117 577 0 0 100 0 \n 0 0 0 282120 134108 5797012 0 0 0 0 \n1007 366 0 0 100 0 \nVmstat procs Section \n•\nr field: Total number of runnable process \n•\nb field: Total number of blocked process \nMemory section \n•\nSwpd field: Used swap space \n•\nFree field: Available free RAM \n•\nBuff field: RAM used for buffers \n•\nCache field: RAM used for filesystem cache \n247\n"
},
{
"page_number": 248,
"text": "Linux 101 Hacks www.thegeekstuff.com\nSwap Section \n•\nSi field: Amount of memory swapped from disk per second \n•\nSo field: Amount of memory swapped to disk per second \nIO Section \n•\nBi field: Blocks received from disk \n•\nBo field: Blocks sent to disk. \nSystem Section \n•\nIn field: Number of interrupts per second. \n•\nCs field: Number of context switches per second. \nCPU Section \n•\nUs field: Time spend running user code. (non-kernel code) \n•\nSy field: Time spent running kernel code. \n•\nId field: Idle time. \n•\nWa field: Time spent waiting for the IO\nAdditional vmstat Examples:\n24 iostat, vmstat and mpstat Examples for Linux \nPerformance Monitoring\nHack 95. Netstat Command \nNetstat command displays the network related information such as \nnetwork connections, routing tables, interface statistics. Following are \nfew examples on how to use netstat command. \n248\n"
},
{
"page_number": 249,
"text": "Linux 101 Hacks www.thegeekstuff.com\nDisplay Active Internet Connections and domain sockets \nusing netstat \n# netstat –an \nActive Internet connections (servers and established) \nProto Recv-Q Send-Q Local Address Foreign Address State \ntcp 0 0 0.0.0.0:5666 0.0.0.0:* LISTEN \ntcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN \ntcp 0 0 0.0.0.0:4086 0.0.0.0:* LISTEN \nskipped.. \nActive UNIX domain sockets (servers and established) \nProto RefCnt Flags Type State I-Node \nPath \nunix 2 [ ACC ] STREAM LISTENING 7894 \n/tmp/.font-unix/fs7100 \nunix 2 [ ACC ] STREAM LISTENING 9662 \n/tmp/.gdm_socket \nunix 2 [ ACC ] STREAM LISTENING 10897 \n@/tmp/fam-root- \nDisplay Active Connections with Process ID and Program \nName \nThis could be very helpful to identify which program has initiated a \nspecific network connection. \n# netstat -tap \nActive Internet connections (servers and established) \nProto Recv-Q Send-Q Local Address Foreign Address \nState PID/Program name \ntcp 0 0 *:nrpe *:* \nLISTEN 16277/xinetd \ntcp 0 0 localhost.localdomain:smtp *:* \nLISTEN 7263/sendmail: acce \n249\n"
},
{
"page_number": 250,
"text": "Linux 101 Hacks www.thegeekstuff.com\ntcp 34 0 localhost.localdomain:54221 \nlocalhost.localdomain:4089 CLOSE_WAIT 29881/httpd \ntcp 0 3216 dev-db:ssh cpe-76-94-\n215-154.soca:4682 ESTABLISHED 11717/sshd: ramesh \nDisplay Routing Table \n# netstat –-route \nKernel IP routing table \nDestination Gateway Genmask Flags MSS irtt Iface \n192.168.1.0 * 255.255.255.0 U 0 0 eth0 \n162.244.0.0 * 255.255.0.0 U 0 0 eth0 \ndefault 192.168.1.1 0.0.0.0 UG 0 0 eth0 \nDisplay RAW network statistics \n# netstat --statistics --raw \nIp: \n 11080343 total packets received \n 0 forwarded \n 1 with unknown protocol \n 0 incoming packets discarded \n 11037744 incoming packets delivered \n 11199763 requests sent out \nIcmp: \n 577135 ICMP messages received \n 64 input ICMP message failed. \n ICMP input histogram: \n destination unreachable: 537 \n timeout in transit: 65 \n source quenches: 2 \n echo requests: 576476 \n echo replies: 12 \n250\n"
},
{
"page_number": 251,
"text": "Linux 101 Hacks www.thegeekstuff.com\n timestamp request: 3 \n address mask request: 3 \n 581558 ICMP messages sent \n 0 ICMP messages failed \n ICMP output histogram: \n destination unreachable: 5079 \n echo replies: 576476 \n timestamp replies: 3 \nMisc Netstat Commands \n•\n# netstat –-tcp –-numeric List of TCP connection to and from the \nmachine. \n•\n# netstat --tcp --listening –-programs Display TCP port that the \nserver is listening on along with the program that is listening on \nthat particular port. \n•\n# netstat –rnC Display the routing cache \nAdditional Netstat Examples:\n10 Netstat Command Examples\nHack 96. Sysctl Command \nLinux kernel parameter can be changed on the fly using sysctl \ncommand. Sysctl helps to configure the Linux kernel parameters during \nruntime. \n# sysctl –a \ndev.cdrom.autoclose = 1 \nfs.quota.writes = 0 \nkernel.ctrl-alt-del = 0 \nkernel.domainname = (none) \n251\n"
},
{
"page_number": 252,
"text": "Linux 101 Hacks www.thegeekstuff.com\nkernel.exec-shield = 1 \nnet.core.somaxconn = 128 \nnet.ipv4.tcp_window_scaling = 1 \nnet.ipv4.tcp_wmem = 4096 16384 131072 \nnet.ipv6.route.mtu_expires = 600 \nsunrpc.udp_slot_table_entries = 16 \nvm.block_dump = 0 \nModify Kernel parameter in /etc/sysctl.conf for permanent \nchange \nAfter modifying the kernel parameter in the /etc/sysctl.conf, execute \nsysctl –p to commit the changes. The changes will still be there after the \nreboot. \n# vi /etc/sysctl.conf \n# sysctl –p \nModify kernel parameter temporarily \nTo temporarily modify a kernel parameter, execute the following \ncommand. Please note that after reboot these changes will be lost. \n# sysctl –w {variable-name=value} \nHack 97. Nice Command \nKernel decides how much processor time is required for a process based \non the nice value. Possible nice value range is: -20 to 20. A process that \nhas a nice value of -20 is very high priority. The process that has a nice \nvalue of 20 is very low priority. \nUse ps axl to display the nice value of all running process as shown \nbelow. \n# ps axl \n252\n"
},
{
"page_number": 253,
"text": "Linux 101 Hacks www.thegeekstuff.com\nF UID PID PPID PRI NI VSZ RSS WCHAN STAT TTY \nTIME COMMAND \n4 0 1 0 16 0 2172 552 - S ? \n0:17 init [5] \n1 0 3 1 34 19 0 0 ksofti SN ? \n3:18 [ksoftirqd/0] \n1 0 10 1 5 -10 0 0 worker S< ? \n0:01 [events/0] \n4 0 5145 1 25 10 32124 18592 - SNs ? \n0:08 /usr/bin/python /usr/bin/rhn-applet-gui --sm-client-\nid default4 \n4 0 5147 5142 16 0 3528 604 - S ? \n0:00 /sbin/pam_timestamp_check -d root \n1 503 17552 4180 16 0 14208 3920 - S ? \n0:01 /home/www/apache2/bin/httpd -f \n/home/www/apache2/conf/httpd.conf -k start \nHow to assign a low priority to a shell-script? (higher nice \nvalue) \nIn the example below, when I started the nice-test.sh script in the \nbackground, it took the nice value of 0. \n$ ./nice-test.sh & \n[3] 13009 \n$ ps axl | grep nice-test \n0 509 13009 12863 17 0 4652 972 wait S pts/1 \n0:00 /bin/bash ./nice-test.sh \n[Note: 6th column with value 0 is the nice.] \nNow, let us execute the same shell script with a different nice value as \nshown below. \n$ nice -10 ./nice-test.sh & \n[1] 13016 \n253\n"
},
{
"page_number": 254,
"text": "Linux 101 Hacks www.thegeekstuff.com\n$ ps axl | grep nice-test \n0 509 13016 12863 30 10 4236 968 wait SN pts/1 \n0:00 /bin/bash ./nice-test.sh \n[Note: 6th column with value 10 is the nice value for the \nshell-script.] \nHow to assign a high priority to a shell-script? (Lower nice \nvalue) \nIn the following example, let us assign a nice value of -10 (minus 10) to \nthe nice-test.sh shellscript. \n$ nice --10 ./nice-test.sh & \n[1] 13021 \n$ nice: cannot set priority: Permission denied \nNote: Only root user can set a negative nice value. Login as root and try \nthe same. Please note that there is a double dash before the 10 in the \nnice command below. \n# nice --10 ./nice-test.sh & \n[1] 13060 \n# ps axl | grep nice-test \n4 0 13060 13024 10 -10 5388 964 wait S< pts/1 \n0:00 /bin/bash ./nice-test.sh \n[Note: 6th column with value -10 is the nice value of the \nshell-script.] \nHack 98. Renice Command \nRenice alters the scheduling priority of a running process. \n254\n"
},
{
"page_number": 255,
"text": "Linux 101 Hacks www.thegeekstuff.com\nHow to decrease the priority of a running process? \n(Increase nice) \nIn the example below, an existing shell-script is running at nice value of \n10. (6th column in the ps output) \n $ ps axl | grep nice-test \n0 509 13245 13216 30 10 5244 968 wait SN pts/1 \n0:00 /bin/bash ./nice-test.sh \nTo increase the nice value (thus reducing the priority), execute the \nrenice command as shown below. \n$ renice 16 -p 13245 \n13245: old priority 10, new priority 16 \n$ ps axl | grep nice-test \n0 509 13245 13216 36 16 5244 968 wait SN pts/1 \n0:00 /bin/bash ./nice-test.sh \n[Note: Now, the 6th column of the nice-test.sh (PID 13245) \nshows the new nice value of 16.] \nHow to increase the priority of a running process? \n(Decrease nice) \nIn the example below, an existing shell-script is running at a nice value \nof 10. (6th column in the ps output) \n$ ps axl | grep nice-test \n0 509 13254 13216 30 10 4412 968 wait SN pts/1 \n0:00 /bin/bash ./nice-test.sh \nIn increase the priority, give a lower nice value as shown below. \nHowever, only root can increase the priority of a running process, else \nyou’ll get the following error message. \n$ renice 5 -p 13254 \n255\n"
},
{
"page_number": 256,
"text": "Linux 101 Hacks www.thegeekstuff.com\nrenice: 13254: setpriority: Permission denied \nLogin as root to increase the priority of a running \nprocess \n$ su - \n# renice 5 -p 13254 \n13254: old priority 10, new priority 5 \n# ps axl | grep nice-test \n0 509 13254 13216 25 5 4412 968 wait SN pts/1 \n0:00 /bin/bash ./nice-test.sh \n[Note: The 6th column now shows a lower nice value of 5 \n(increased priority)] \nHack 99. Kill Command \nkill command can be used to terminate a running process. Typically this \ncommand is used to kill processes that are hanging and not responding. \nSyntax: kill [options] [pids|commands] \nHow to kill a hanging process? \nFirst, identify the process id of the particular process that you would like \nto kill using the ps command. Once you know the process id, pass it as a \nparameter to the kill command. The example below shows how to kill \nthe hanging apache httpd process. Please note that typically you should \nuse “apachectl stop” to stop apache. \n# ps aux | grep httpd \nUSER PID %CPU %MEM VSZ RSS TTY STAT START \nTIME COMMAND \napache 31186 0.0 1.6 23736 17556 ? \nS Jul26 0:40 /usr/local/apache2/bin/httpd \n256\n"
},
{
"page_number": 257,
"text": "Linux 101 Hacks www.thegeekstuff.com\napache 31187 0.0 1.3 20640 14444 ? \nS Jul26 0:37 /usr/local/apache2/bin/httpd \n# kill 31186 31187 \n \nPlease note that the above command tries to terminate the process \ngraciously by sending a signal called SIGTERM. If the process does not \nget terminated, you can forcefully terminate the process by passing a \nsignal called SIGKILL, using the option -9 as shown below. You should \neither be the owner of the process or a privileged user to kill a process. \n# kill -9 31186 31187 \nAnother way to kill multiple processes easily is by adding the following \ntwo functions to the .bash_profile. \nfunction psgrep () \n{ \n ps aux | grep \"$1\" | grep -v 'grep' \n} \nfunction psterm () \n{ \n [ ${#} -eq 0 ] && echo \"usage: $FUNCNAME STRING\" && \nreturn 0 \n local pid \n pid=$(ps ax | grep \"$1\" | grep -v grep | awk '{ print \n$1 }') \n echo -e \"terminating '$1' / process(es):\\n$pid\" \n kill -SIGTERM $pid \n} \nNow do the following, to identify and kill all httpd processes. \n# psgrep http \n257\n"
},
{
"page_number": 258,
"text": "Linux 101 Hacks www.thegeekstuff.com\nUSER PID %CPU %MEM VSZ RSS TTY STAT START \nTIME COMMAND \napache 31186 0.0 1.6 23736 17556 ? \nS Jul26 0:40 /usr/local/apache2/bin/httpd \napache 31187 0.0 1.3 20640 14444 ? \nS Jul26 0:37 /usr/local/apache2/bin/httpd \n# psterm httpd \nterminating 'httpd' / process(es): \n31186 \n31187 \nAdditional Kill Examples: \n4 Ways to Kill a Process – kill, killall, pkill, xkill\nHack 100. Ps Command\nps command (process status) will display snapshot information of all \nactive processes. \nSyntax: ps [options] \nHow to display all the processes running in the system? \nUse \"ps aux\", as shown below. \n# ps aux | more \nUSER PID %CPU %MEM VSZ RSS TTY STAT START \nTIME COMMAND \nroot 1 0.0 0.0 2044 588 ? Ss \nJun27 0:00 init [5] \napache 31186 0.0 1.6 23736 17556 ? S \nJul26 0:40 /usr/local/apache2/bin/httpd \n258\n"
},
{
"page_number": 259,
"text": "Linux 101 Hacks www.thegeekstuff.com\napache 31187 0.0 1.3 20640 14444 ? S \nJul26 0:37 /usr/local/apache2/bin/httpd \nYou can also use \"ps -ef | more\", to get a similar output \n Print the Process Tree \nYou can use either ps axuf or ps –ejH to display processes in a tree \nformat. The tree structure will help to visualize the process and it’s \nparent process immediately. For clarity purpose, few columns have been \ncut-off in the output below. \n# ps axuf \nroot Oct14 0:00 /opt/VRTSralus/bin/beremote \nroot Oct14 0:00 \\_ /opt/VRTSralus/bin/beremote \nroot Oct14 0:00 \\_ /opt/VRTSralus/bin/beremote \nroot Oct14 0:00 \\_ /opt/VRTSralus/bin/beremote \nroot Oct14 0:01 \\_ /opt/VRTSralus/bin/beremote \nroot Oct 14 0:00 \\_ /opt/VRTSralus/bin/beremote \nroot Dec03 0:01 /usr/local/sbin/sshd \nroot Dec22 1:08 /usr/local/sbin/sshd \nroot 23:35 0:00 \\_ /usr/local/sbin/sshd \n511 23:35 0:00 \\_ -bash \n511 \\_ ps axuf \nNote: You can also use pstree command to display process in tree \nstructure. \nView Processes Owned by a Particular User \nThe following command displays all the process owned by Linux user-\nname: oracle. \n$ ps U oracle \nPID TTY STAT TIME COMMAND \n259\n"
},
{
"page_number": 260,
"text": "Linux 101 Hacks www.thegeekstuff.com\n5014 ? Ss 0:01 /oracle/bin/tnslsnr \n 7124 ? Ss 0:00 ora_q002_med \n8206 ? Ss 0:00 ora_cjq0_med \n8852 ? Ss 0:01 ora_pmon_med \n8854 ? Ss 0:00 ora_psp0_med \n8911 ? Ss 0:02 oraclemed (LOCAL=NO) \n View Processes Owned by Current User \nFollowing command displays all the process owned by the current user. \n$ ps U $USER \nPID TTY STAT TIME COMMAND \n10329 ? S 0:00 sshd: ramesh@pts/1,pts/2 \n10330 pts/1 Ss 0:00 -bash \n10354 pts/2 Ss+ 0:00 -bash \n10530 pts/1 R+ 0:00 ps U ramesh \nAdditional PS Examples:\n7 Practical PS Command Examples for Process Monitoring\nHack 101. Sar Command \nSar commands comes with the sysstat package. Make sure sysstat is \ninstalled. If you don’t have sar installed on your system, get it from \nSysstat project. \nSar is an excellent monitoring tool that displays performance data of \npretty much every resource of the system including CPU, memory, IO, \npaging, networking, interrupts etc., \n260\n"
},
{
"page_number": 261,
"text": "Linux 101 Hacks www.thegeekstuff.com\nSar Collects, Reports (displays) and Saves the performance data. Let us \nlook at all the three aspects separately \nSadc - System activity data collector \n/usr/lib/sadc (System activity data collector) command collects the \nsystem data at a specified time interval. This uses the daily activity data \nfile that is located under /va/log/sa/sa[dd], where dd is the current day. \nSa1 shell-script \n/usr/lib/sa1 in-turn calls the /usr/lib/sadcs. sa1 is invoked from the \ncrontab as shown below. Run this every 5 minutes or 15 minutes \ndepending on your need. I prefer to schedule it for every 5 minutes in \nthe cron tab as shown below. \n*/5 * * * * root /usr/lib/sa/sa1 1 1 \nSa2 shell-script \n/usr/lib/sa2 is a shell script that will write a daily report in the \n/var/log/sa/sa[dd] file, where dd is the current day. Invoke the sa2 from \nthe crontab once a day at midnight. \n# 59 23 * * * root /usr/lib/sa/sa2 –A \nNote: /etc/cron.d/sysstat files comes with the sysstat package that \nincludes some default value for the sa1 and sa2, which you can change \naccordingly. \nDisplay CPU Statistics using Sar Command \n# sar –u \nLinux 2.6.9-42.ELsmp (dev-db) 01/01/2009 \n12:00:01 AM CPU %user %nice %system %iowait \n%idle \n12:05:01 AM all 3.70 0.00 0.85 0.00 \n95.45 \n261\n"
},
{
"page_number": 262,
"text": "Linux 101 Hacks www.thegeekstuff.com\n12:10:01 AM all 4.59 0.00 1.19 0.06 \n94.16 \n12:15:01 AM all 3.90 0.00 0.95 0.04 \n95.11 \n12:20:01 AM all 4.06 0.00 1.00 0.01 \n94.93 \n12:25:01 AM all 3.89 0.00 0.87 0.00 \n95.23 \n12:30:01 AM all 3.89 0.00 0.87 0.00 \n95.23 \n \nSkipped.. \nAverage: all 4.56 0.00 1.00 0.15 \n94.29 \nNote: If you need a break down of the performance data for the \nindividual CPU’s, execute the following command. \n# sar -u -P ALL \nDisplay Disk IO Statistics using sar command \n# sar –d \nLinux 2.6.9-42.ELsmp (dev-db) 01/01/2009 \n12:00:01 AM DEV tps rd_sec/s wr_sec/s \n12:05:01 AM dev2-0 1.65 1.28 45.43 \n12:10:01 AM dev8-1 4.08 8.11 21.81 \nSkipped.. \nAverage: dev2-0 4.66 120.77 69.45 \nAverage: dev8-1 1.89 3.17 8.02 \n262\n"
},
{
"page_number": 263,
"text": "Linux 101 Hacks www.thegeekstuff.com\nDisplay networking Statistics using sar command \n# sar -n DEV | more \nLinux 2.6.9-42.ELsmp (dev-db) 01/01/2009 \n12:00:01 AM IFACE rxpck/s txpck/s rxbyt/s \ntxbyt/s rxcmp/s txcmp/ s rxmcst/s \n12:05:01 AM lo 0.17 0.16 25.31 \n23.33 0.00 0.0 0 0.00 \n12:10:01 AM eth0 52.92 53.64 10169.74 \n12178.57 0.00 0.00 0.00 \n \n# sar -n SOCK |more \nLinux 2.6.9-42.ELsmp (dev-db) 01/01/2009 \n12:00:01 AM totsck tcpsck udpsck rawsck ip-frag \n12:05:01 AM 50 13 3 0 0 \n12:10:01 AM 50 13 4 0 0 \n12:15:01 AM 53 13 5 0 0 \nAdditional SAR Examples:\n10 Useful Sar (Sysstat) Examples for Linux Performance \nMonitoring\n263\n"
},
{
"page_number": 264,
"text": "Linux 101 Hacks www.thegeekstuff.com\nYour Support is Appreciated \nIf you liked this Linux 101 hacks free ebook, and would like to thank me \nand support The Geek Stuff blog, purchase the following eBooks: \nBash 101 Hacks \nBash is the default shell on Linux. If you are \nspending lot of time on Linux environment, you \nshould master the Bash command line features to \nbecome efficient. Apart from being an interactive \nshell, Bash is also a scripting language, which \nallows you to automate your tasks using Bash shell \nscripting. \nBash 101 Hacks is a downloadable eBook that \ncontains 101 practical examples on both Bash \ncommand line and shell scripting.\nGet Your Copy of: Bash 101 Hacks eBook\nSed and Awk 101 Hacks \nIf you are spending lot of time on UNIX / Linux, you’ll \nbe manipulating text files frequently. You may be \nmaking the similar edits on multiple configuration \nfiles on one or more servers. You may be digging \nhuge log files (or data files) looking for certain \ninformation. \nSed and Awk 101 Hacks is a downloadable eBook \nthat contains 101 practical examples on various \nadvanced Sed and Awk features, that will help you \nunderstand everything you need to know about Sed \nand Awk. \nGet Your Copy of: Sed and Awk 101 Hacks eBook\n264\n"
},
{
"page_number": 265,
"text": "Linux 101 Hacks www.thegeekstuff.com\nNagios Core 3 \nYou should implement a robust monitoring solution \nthat will notify you when there is an issue. It should \nalso notify the right people at the right time about a \npotential issue, even before it becomes critical. \nNagios Core 3 eBook is the only guide you’ll ever \nneed to get your IT infrastructure monitored using \nNagios Core, and it will help you to understand \neverything you need to know to implement Nagios \nCore 3. \nGet Your Copy of: Nagios Core \n \n 3 eBook\n \n \nVim 101 Hacks \nVim editor is very powerful editor that will make you \nextremely productive once you take some time to \nlearn and understand its features. If you are like \nmost people, you would like to have a structured \nway of learning this powerful editor and take \nadvantage of all its features. \nVim 101 Hacks is a downloadable eBook that \ncontains 101 practical examples on various \nadvanced Vim features that will make you fast and productive in the Vim \neditor.\nGet Your Copy of: Vim 101 Hack\n \n s eBook\n \n \n265\n"
},
{
"page_number": 266,
"text": "Linux 101 Hacks www.thegeekstuff.com\n10 Amazing and Essential Linux \nBooks \nFor further reading on Linux, I recommend the following books. The 10 \nLinux books mentioned here by no means are comprehensive or \nauthoritative list. But, these 10 Books are few of my favorites that I \nenjoyed reading over the years and I strongly believe will enhance your \ntechnical abilities on Linux, if you have not read them yet. \n1.\nSSH, The Secure Shell\n \n , by Daniel J. Barrett, Richard E. \nSilverman and Robert G. Byrnes. This is hands-down the \nbest book on SSH. This book explains both theoretical and \npractical aspects of SSH. Using SSH as an end-user is fairly \nstraight forward . But, configuring SSH as an administrator is \ncomplex and involves a detailed understanding of SSH. This \nis a must read for any system administrator. The examples in \nthis book show exactly what needs to be done differently for \nthe different flavors of SSH such as SSH1, SSH2 and \nOpenSSH. \n2.\nEssential System Administration\n \n , by Æleen Frisch. This \nis an excellent book for those who like to become a Unix \nSystem Administrator. This book covers all the typical system \nadministration tasks. This is a perfect companion when you \nare dealing with multiple flavors of Unix, as it has examples \nfor AIX, FreeBSD, HP-UX, Linux, Solaris and Tru64. I’ve used \nthe pocket version of this book — Essential System \nAdministration Pocket Reference, when I was managing \nmultiple flavors of Unix systems at the same time. \n3.\nLinux Server Hacks\n \n , Volume One, by Rob Flickenger. \n100 awesome practical hacks packed in one book. Setup a \nLinux test bed and try out all these hacks. These hacks are \nneatly grouped into different sections — Server Basics, \nRevision Control, Backups, Networking, Monitoring, SSH, \nScripting, and Information Servers. Once you’ve mastered \nthese hacks, you should absolutely read Linux Server Hacks, \nVolume Two, by William von Hagen and Brian Jones, which has \n100 Linux hacks focused on authentication, monitoring, \nsecurity, performance and connectivity. \n4.\nDNS and BIND\n \n , by Cricket Liu and Paul Albitz. Several \nyears ago, I configured my first DNS by reading online \ndocumentation. I brought this book to understand how DNS \n266\n"
},
{
"page_number": 267,
"text": "Linux 101 Hacks www.thegeekstuff.com\nand BIND works. I’ve already upgraded this book twice when \na newer edition was released. This should definitely be in your \nlibrary, if you are a serious system administrator. \n5.\nUnderstanding the Linux Kernel\n \n , by Daniel Bovet and \nMarco Cesati. If you are a serious developer on Linux \nenvironment or a sysadmin, this is a must read. This books \nexplains the inner workings of the Linux Kernel 2.6 in a \nstructured and logical way. This talks about how Kenel \nhandles the Memory Management, Process scheduling, I/O \narchitecture and Block devices. Overall this book is a treat for \ngeeks who are curious to explore what is under the hood of \nLinux. \n6.\nThe AWK Programming Language\n \n , by Alfred V. Aho, \nBrian W. Kernighan, Peter J. Weinberger. This is a classic \nbook written written by the authors of Awk. If you are dealing \nwith text based data files on Linux environment, mastering \nAwk will help you to quickly create scripts to automate your \ndata file manipulation jobs.\n7.\nLinux Cookbook\n \n , by Carla Schroder. This book covers \nLinux features from both users and system administrators \npoint of view. There are two chapters dedicated for installing \nand managing software on RPM-based system and Debian. If \nyou use RedHat, the Linux Pocket Guide, by Daniel J. Barrett is \nan excellent addition to your library, which covers all the \nessential Linux command with a sample usage. \n8.\nLinux Firewalls\n \n , by Michael Rash. To build a secure Linux \nsystem, you must read this book. There are quiet few books \nout there for iptables. But, this one talks specifically about the \nfundamentals of how to configure an Intrusion Detection \nSystem using iptables, psad and fwsnort. If you want a \ncomprehensive handy reference of all the things iptables can \ndo with specific examples, Linux Iptables Pocket Reference, \nby Gregor N. Purdy is the best. \n9.\nLinux Administration Handbook\n \n , by Evi Nemeth, Garth \nSnyder and Trent R. Hein. During my early days of system \nadministration, I’ve referred this book frequently. This is \npretty detailed book with close to 1000 pages and 30 \nchapters that are nicely grouped together in three high level \nsections — Basic Administration, Networking and Bunch O’ \nStuff. \n10. Beginning Ubuntu Linux\n \n , by Keir Thomas and Jaime \nSicam. For those who like to transition from Windows to \n267\n"
},
{
"page_number": 268,
"text": "Linux 101 Hacks www.thegeekstuff.com\nLinux, install Ubuntu Linux on one of your old laptop or \ndesktop and get this book. I strongly believe in spreading the \nnews about Linux to those who don’t use it. If you want any of \nyour loved ones or friends to learn Linux, install Ubuntu on an \nold laptop and give this book as a gift to them. They’ll \ndefinitely be very thankful to you. \nMore Recommended Books:\nFor Additional Linux and Open Source Related Books that \nI recommend, visit The Geek Stuff Book Store at Amazon\n268\n"
},
{
"page_number": 269,
"text": "Linux 101 Hacks www.thegeekstuff.com\nExtended Reading\nFollowing are few articles from the The Geek Stuff blog for your \nextended reading. Check out The Geek Stuff Archives section for more \narticles.\n1.\n50 Linux Sysadmin Tutorials\n \n \n2.\n50 Most Frequently Used Linux Commands (With Examples)\n \n \n3.\nUnix LS Command: 15 Practical Examples\n \n \n4.\nTurbocharge PuTTY with 12 Powerful Add-Ons\n \n \n5.\nwget Tutorial: 15 Awesome Examples to Download Files from\n \n \nInternet\n6.\nPing Tutorial: 15 Effective Ping Command Examples\n \n \n7.\nNagios - Enterprise Monitoring Solution\n•\nNagios Jumpstart Guide\n \n \n•\nMonitor Window Server\n \n \n•\nMonitor Linux Server\n \n \n•\nMonitor Network Switch\n \n \n•\nMonitor VPN Device\n \n \n8.\nPerform SSH and SCP without entering password:\n•\nFrom openSSH to openSSH\n \n \n•\nFrom openSSH to SSH2\n \n \n•\nFrom SSH2 to SSH2\n \n \n9.\nHello World Examples\n \n (Learn a programming language)\n10. UNIX Sed Tips and Tricks\n \n \n11. Ubuntu Tips and Tricks\n \n \n12. MySQL Tutorials\n \n \n13. PostgreSQL Tutorials\n \n \n14. Vi / Vim Tips and Tricks\n \n \n•\nVim Macro Tutorial: How To Record and Play\n \n \n•\nHow To Use Vim as Perl IDE and C/C++ IDE\n•\nAutomatic Word Completion in Vim\n \n \n269\n"
},
{
"page_number": 270,
"text": "Linux 101 Hacks www.thegeekstuff.com\n15. 3 Steps to Add Custom Header to a File Using Vim\n \n \n16. The Ultimate Guide for Creating Strong Passwords\n \n \n17. 6 Steps to Secure Your Home Wireless Network\n \n \n18. Firefox Add-On: Hire 7 Personal Bodyguards to Browse Internet\n \n \nSecurely\n19. Tripwire Tutorial: Linux Host Based Intrusion Detection System\n \n \n20. Midnight Commander (mc) Guide: Powerful Text based File\n \n \nManager for Unix\nMore Linux Articles\nI publish Linux and Open Source articles on an on-going basis on The \nGeek Stuff blog.\nTo get Linux Tips, HowTos, Guides and Tutorials on an on-going basis, \nsubscribe to The Geek Stuff blog. If you subscribe, you will get new \narticles posted on TGS website directly to your inbox or to your RSS \nreader. \nSubscribe to receive free Linux tutorials directly to \nyour email inbox regularly.\n270\n"
},
{
"page_number": 271,
"text": "Linux 101 Hacks www.thegeekstuff.com\nThank You\nI hope you found the Linux 101 Hacks eBook \nhelpful.\nI sincerely appreciate all the support given by \nyou and other regular readers of my \nthegeekstuff.com blog.\nYou have encouraged me in more ways than you know.\nIf you liked this eBook, and would like to support me, consider buying \nmy other eBooks:\n•\nBash 101 Hacks\n \n \n•\nSed and Awk 101 Hacks\n \n \n•\nVim 101 Hacks\n \n \n•\nNagios Core 3\n \n \nIf you have any suggestions, or feedback, or questions while reading this \nebook, don't hesitate to reach out to me. You can connect with me on \nthe following:\n•\nTwitter (@t\n hegeekstuff\n \n )\n•\nFacebook page\n \n \nIf you want to write to me directly, you can use this contact form to \nreach out to me.\nRamesh Natarajan\nramesh@thegeekstuff.com\n271\n"
}
]
}