Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
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

Arrow left icon
Profile Icon Andrew Mallett
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (13 Ratings)
Paperback Nov 2014 174 pages 1st Edition
eBook
$16.99 $18.99
Paperback
$28.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Andrew Mallett
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (13 Ratings)
Paperback Nov 2014 174 pages 1st Edition
eBook
$16.99 $18.99
Paperback
$28.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$16.99 $18.99
Paperback
$28.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 and vi

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

Description

If you are a Linux administrator who is looking to gain knowledge that differentiates yourself from the crowd, then this is the book for you. Beginners who have a keen interest to learn more about Linux administration will also progress quickly with this resourceful learning guide.

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

Product Details

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

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 138.97
Mastering CentOS 7 Linux Server
$54.99
CentOS System Administration Essentials
$28.99
CentOS 6 Linux Server Cookbook
$54.99
Total $ 138.97 Stars icon

Table of Contents

12 Chapters
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
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(13 Ratings)
5 star 53.8%
4 star 15.4%
3 star 23.1%
2 star 7.7%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Bret W. Apr 12, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent book and extremely well written, however these were not suitable for my web server purposes as very broad. Returned with no quibbles and wouldn't hesitate to buy again.
Amazon Verified review Amazon
modernistShambles Mar 14, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Clearly written.
Amazon Verified review Amazon
Mike O Oct 22, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I don't think you could find a more knowledgeable guide to Linux than Andrew Mallett. Seriously... he's awesome, and so are his books and videos.
Amazon Verified review Amazon
John Jul 03, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've watched a couple of Andrew's videos and he is very good at explaining things in an easy to grasp manner. He is clearly a person who not only has great technical skills but also has the ability to pass that knowledge on to others which is very rare indeed! I have to say the book was every bit as good. At times entertaining with sprinklings of Andrew's sense of humour but very easy to follow and a very good read. If you enjoy working with Linuc and CentOS in particular then you will love this book. I look forward to reading and watching more of Andrew's work.
Amazon Verified review Amazon
Luke_Vidler Jun 20, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is definitely one of the better Linux books I've read. Covers the Essentials really really well, the goal of the author is comprehension of the essential concepts, with the occasional side of cool hacks. Succeeds in gifting the serious student with confidence that would have been missing otherwise. Great resource and just the right length for me.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.