Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
CentOS System Administration Essentials
CentOS System Administration Essentials

CentOS System Administration Essentials: Become an efficient CentOS administrator by acquiring real-world knowledge of system setup and configuration

eBook
$18.99 $12.99
Print
$28.99
Subscription
$15.99 Monthly

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Black & white paperback book shipped to your address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now
Table of content icon View table of contents Preview book icon Preview Book

CentOS System Administration Essentials

Chapter 1. Taming vi

You may have some experience with vi, or what is now known as Vim (which is when simply put—vi improved). All too often, I find that those first experiences have never been good ones or to be looked back upon with much fondness. Guiding you through the initially unfathomable regime of vi, we are going to make sure that you are the master of vi and you leave wanting to use this tool from the gods. vi is like everything else in the sense that you just need to stick with it in the early days and keep practicing. Remember how you persevered for many hours riding your bicycle as a toddler and became a master, despite a few bruised knees? I want you to persevere with vi too. We will start with a little command-line magic to make the whole command-line interface (CLI) experience a better one. We will then be ready to start our black-belt experience in vi.

In this chapter, we will go through the following topics:

  • CLI trickery – shortcuts that you will love

  • Vim and vi: In this section, you will learn to differentiate between these twins and meet their graphical cousin

  • Getting the .vimrc setup the way you like

  • Search and replace: In this section, you will learn how to quickly find and replace text within files from both inside and outside Vim

  • Learning to remove extraneous comments from a file with a few deft key strokes

CLI trickery – shortcuts that you will love


So before we dice into the wonderful world of text editing that is vi, we will warm up with a few exercises on the keyboard. Linux is my passion, as is automation. I am always keen to create scripts to carry out tasks so that those tasks become repeatedly correct. Once the script is created and tested, we will have the knowledge and faith that it will run in the same way every time and we will not make mistakes or miss critical steps, either because it gets boring or we are working late on a Friday night and just want to go home. Scripting itself is just knowing the command line well and being able to use it at its best. This truth remains across all systems that you will work with.

On the command line, we may try a little more black magic by executing the following command:

$ cd dir1 || mkdir dir1 && cd dir1

With this, we have used the cd command to enter the dir1 directory. The double pipe or vertical bar indicates that we will attempt the next command only if the first command fails. This means that if we fail to switch to the dir1 directory, we will run the mkdir dir1 command to create it. If the directory creation succeeds, we then change into that directory.

Tip

The || part denotes that the second command will run only on the failure of the first. The && part denotes that the second command will run only if the first command succeeds.

The command history is a little more and hugely better than just an up arrow key! Consider the following commands:

$ mkdir dir1
$ cd !$

The !$ part represents the last argument, so in this way, the second line evaluates to the following:

$ cd dir1

In this way, we can rewrite the initial command sequence, by combining both concepts, to create the following command:

$ cd dir1 || mkdir !$ && cd !$

We can repeat the last command as well as the last argument. More importantly, we can specify the start characters for the last command. If it was merely the last command, then the up arrow key would suffice. If we were working on a web server configuration, we may want to edit the configuration file with vi, start the service, and then test with a command-line browser. We can represent these tasks using the following three commands:

# vi /etc/httpd/conf/httpd.conf
# service httpd restart
w3m localhost

Having run these three commands in the correct order, hoping for success, we may notice that we still have issues and that we need to start re-editing the configuration file for Apache, the web server. We can now abbreviate the command list to the following:

# !v
# !s
# !w

The !v command will rerun the last command in my history that begins with a v, and likewise with s and w. This way, we can appear to be terribly proficient and working really quickly, thus gaining more time to do what really interests us, perhaps a short 9 holes?

In a similar fashion to our first glance at the history using the !$ symbols to represent the last argument, we can use !?73. This would look for 73 anywhere as an argument or part of an argument. With my current history, this would relate to the date command we ran earlier. Let's take a look:

$ !?73

With my history, the sequence will expand to and run the following command:

$ date --date "73 days ago"

Looking at my command history from the last command run to the first, we search for 73 anywhere as a command argument. We make a note that we exclusively look for 73, meaning we are looking for the character 7 followed by the character 3. We have to then bear in mind that we would also match 273 or 733 if they existed in my history.

Having mastered a little of the Bash shell history functions, we should practice to make this second nature.

Vim and vi


Ah yes, Vim and vi! They sound like some ancient mystic potion that ensures long life and wisdom. Alas though, they are not.

The command-line text editor vi was first written in 1976 and became part of the first release of BSD Unix in 1978. Even though it is command line driven and with no Graphical User Interface (GUI) or menu, a 2009 survey conducted by Linux Journal found that vi was the most popular editor, beating even gedit, the GUI GNOME editor, into second place. I am not averse to the GUI, but I find a GUI editor to be restrictive and slow. I can honestly say that the majority of, if not all, tasks can be performed by me more quickly in vi.

That being said, in CentOS, you will not find vi; vi is purely a default alias that is provided for convenience, and links to the vim command. We can view this on my CentOS 6.5 console using the following command:

$ alias | grep vi

The output of the command should look similar to the following screenshot:

Vim is a contraction of Vi IMproved and was first publicly released in 1991 and authored by Bram Moolenaar, initially targeted at the Amiga system. It has been common in the Linux platform since the early 2000s. As the name suggests, it is based on vi and is improved; on CentOS, it is distributed with the vim-enhanced package. These improvements are most commonly useful with the syntax-highlighting feature available for languages such as PERL, Python, and PHP. Another such improvement is that it can work traditionally on the command line or with a GUI frontend. To install the graphical interface for Vim, you will need to add the vim-X11 package as follows:

# yum install -y vim-X11

Tip

One limitation, of course, is that you will require the X11 server to be running. In an enterprise, the server will often run without a GUI and you can connect using secure shell to a command-line shell only.

If you are new to vi, then using the graphical version can be helpful, as the menus also display the command-line shortcuts. To edit a file with vi or Vim on the command line, we can simply use a command similar to the following:

$ vi <filename-to-edit>

It is possible to use the graphical version of an editor when you are working on the CentOS desktop as follows:

$ gvim <filename-to-edit>

or

$ vimx -g <filename-to-edit>

I would recommend using the gvim command, as it doesn't require the additional option and causes less confusion. Starting vimx without the -g option just starts the normal Vim program.

Getting the .vimrc setup the way you like


As with many programs in Linux, Vim has the option to read settings from a run-control file. This can be centralized via the /etc/vimrc file, or for each user via the ~/.vimrc file. With this file, especially with our own version, you can customize how Vim appears and controls its functionalities.

Firstly, we will look at line numbering. Often when we edit a file, we do so as the console has reported an error on a particular line just after we have tried running a script or starting a service; we know we have a syntax error. Let's say we want to go directly to the offending line 97 of the test.php file. Then, we would duly type:

$ vi +97 test.php

This is assuming that we were in the same directory as our file. Similarly, should we want to go directly to the first occurrence of the word install within the readme file, we could issue the following command:

$ vi +/install readme

Then, as if by magic, we are transported to the correct line that we require. However, in the case of the word search, the word that was search is highlighted in color. If that is not desirable, then we can simply turn off that feature. Within Vim, we can type:

:nohlsearch

If there are settings that we want to make permanent within Vim, we can edit the .vimrc file in our home directory. This is our own personal settings file and as such, changes made here will not affect anyone else. If we want to affect system-wide settings, then we can use the /etc/vimrc file. Try adding the following line to the ~/.vimrc file to persistently disable the highlight search:

set nohlsearch

With this addition, each time we start Vim, the setting is ready for us. As we view our files though, from within Vim, we may prefer to have line numbering turned on. Sometimes this makes life easier, but other times, we may prefer to have line numbering off, especially in cases where we have lines starting with numbers (because the display can become confusing). To enable line numbering, run the following command:

:set number

To turn line numbering off, we can use the following command:

:set nonumber

As before, we can always put the desired start-up value in the .vimrc file. However, before we do this, let's look at key mappings within Vim and how we can create a shortcut to toggle line numbering on and off. We would like to create a mapping for the normal mode in Vim. This is the mode when we first enter Vim and we are not editing, just navigating the file; using the Esc key, we can always return to the normal mode. Execute the following command:

:nmap <C-N> : set invnumber<CR>

The nmap command denotes that we are making a mapping for the normal mode only. We are mapping the Ctrl + N keys to run the sub command :set invnumber followed by <CR>.

With this in place, we can now use the combination of Ctrl + N to toggle line numbering on and off. Now we are really starting to make some steam with this product, and you can gain some appreciation of why it is so popular. Before we make the final edit to the .vimrc file, we will see how to navigate lines by number while in vi or Vim. Making sure that we are in the normal mode using the Esc key, we can use 2G or 2gg to navigate to line 2 of the current file; likewise, 234G or 234gg would go to line 234 and G or gg would navigate to the end of the file. Simple but not simple enough; I would prefer to type the line number followed by the Enter key. For this, we map the Enter key to G. If we choose to use the Enter key without a preceding number, then we are taken directly to the end of the document, just as we would is we used the key G by itself. Execute the following command:

:nmap <CR> G

Now we simply type in the desired line number followed by Enter. This in turn is interpreted as the number followed by G. In this way, we can navigate easily to the correct line. We can persist this setting by adding the following text to the .vimrc file, which should now read similar to the following text as we review all the settings made within this subsection:

set nohlsearch number
nmap <C-N> : set invnumber<CR>
nmap <CR> G

Now sit back and enjoy what you have achieved, remembering though that practice is the key to knowledge being retained.

Search and replace


So we are not exactly on a "search and destroy" mission, but if it helps by adding a little enjoyment to our learning, then we can embark upon a search and replace mission. Linux has a huge amount of power available on the command line and nothing less than the stream editor, sed. Even without entering the Vim editor, we can search for and replace text in a single file or even across multiple files. Not having to use an interactive editor opens up more administrative scope to us by being able to script updates across a single or many servers. The functionality we have in the sed command is available to us for use from within Vim or as a standalone application. We will be learning in this subsection how to search for and replace text within files using sed and from within Vim, building skills that we can use across CentOS and other operating systems including OS X on the Mac.

Firstly, let's take a scenario that we have recently changed our company name and we need to change all the references of Dungeons in a text document to Dragons. Using sed, we could run the command directly from the console:

$ sed -i 's/Dungeons/Dragons/g' /path/file

This will read the file line by line, replacing all occurrences of the string Dungeons with Dragons. The -i option allows for in-pace edits, meaning we edit the file without the need to redirect the output from sed to a new file. The g option allows for the replacement to occur across all instances of Dragon even if it appears more than once per line.

To do the same within Vim where we have the file open, run the following command:

:%s/Dungeons/Dragons/g

The percent symbol is used to specify the range as the whole document; whereas if we use the following command, we would only search lines 3 through 12 inclusive of the search string. In this case, the range is said to be lines 3 to 12 whereas with %, the range is the complete document.

:3,12s/Dungeons/Dragons/g

The range can be very useful when perhaps we want to indent some code in a file. In the following line, we again search lines 3 through to 12 and add a Tab to the start of each line:

:s/3,12s/^/\t/

We have set the range in the previous command within Vim to represent lines 3 to 12 again. These lines may represent the contents of an if statement, for example, that we would like to indent. We search first for the carat symbol, ^ (the start of a line), and replace it with a tab (\t). There is no need for the global option as the start of a line obviously only occurs once per line. Using this method, we can quickly add indents to a file as required, and we are again Zen superheroes of Vim.

Learning to remove extraneous comments from a file with a few deft key strokes


Now that we are the administrator, the Zen master of search and replace, we can use these skills to tidy configuration files that often have many hundreds of commented lines within them. I do not mind documentation but when it becomes such an overwhelming majority, it can take over. Consider the httpd.conf Apache configuration file under /etc/httpd/conf/. This has 675 commented lines. We perhaps want to keep the original file as a reference. So let's first make a copy by executing the following command; we know how to do this from the Preface of this book and if you did not read it, now is your chance to read it before a letter goes home to your parents.

# cd /etc/httpd/conf
# cp httpd.conf   httpd.conf.$(date +%F)

We can easily list the commented lines using the following command that counts the lines that begin with the # sign, a comment:

# egrep -c '^#' httpd.conf

On my system, we see that there are 675 such lines. Using sed or Vim, we can remove the comments, firstly, with sed, as follows:

# sed  -i '/^#/d' httpd.conf

Then, within Vim with the file open, it is a little different:

:g/^#/d

The result is the same in both examples where we have reduced the numbers of lines in the file by about two-thirds.

Summary


In each chapter, I want to make sure that there has been at least one item of value that you feel you can take away with you and use; how did I do in this chapter? If you recall, we have reviewed a few shortcuts that may help us navigate the command history effectively. Quickly, we moved on to discover the text editor vi or, more commonly now, Vim. For those that need a little help getting started with Vim, we additionally have gVim available to use if we are working on the desktop. Customizing any system is important to make us feel that we own the system and it works for us. With Vim, we can use the .vimrc file found in our home directory. We were able to add a little bling to Vim with some extra key mapping and desirable options. From then on, it was straight down to work to see what Vim could do, and how the search and replace and delete options that we reviewed worked.

Left arrow icon Right arrow icon

Key benefits

What you will learn

Conquer the command line using shortcuts in the shell and within the editor Vim Analyze the booting of CentOS utilizing MBR, GRUB, and Plymouth Gain an understanding of the filesystem structure of hard links, inodes, and data using stat and ls Manage your software installations with YUM Handle your services as they begin to migrate from System V scripts Establish centralized account information using openLDAP directory services Centralize the configuration management of CentOS using Puppet, enabling updates from Puppet Master to be distributed to the clients
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected

Publication date : Nov 25, 2014
Length 174 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781783985920
Vendor :
The CentOS Project

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Black & white paperback book shipped to your address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details


Publication date : Nov 25, 2014
Length 174 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781783985920
Vendor :
The CentOS Project

Table of Contents

18 Chapters
CentOS System Administration Essentials Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. Taming vi Chevron down icon Chevron up icon
2. Cold Starts Chevron down icon Chevron up icon
3. CentOS Filesystems – A Deeper Look Chevron down icon Chevron up icon
4. YUM – Software Never Looked So Good Chevron down icon Chevron up icon
5. Herding Cats – Taking Control of Processes Chevron down icon Chevron up icon
6. Users – Do We Really Want Them? Chevron down icon Chevron up icon
7. LDAP – A Better Type of User Chevron down icon Chevron up icon
8. Nginx – Deploying a Performance-centric Web Server Chevron down icon Chevron up icon
9. Puppet – Now You Are the Puppet Master Chevron down icon Chevron up icon
10. Security Central Chevron down icon Chevron up icon
11. Graduation Day Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Top Reviews
No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela