Christopher Negus - Linux Bible

Здесь есть возможность читать онлайн «Christopher Negus - Linux Bible» — ознакомительный отрывок электронной книги совершенно бесплатно, а после прочтения отрывка купить полную версию. В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: unrecognised, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Linux Bible: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Linux Bible»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

The industry favorite Linux guide
Linux Bible, 10th Edition This useful guide assumes a base of little or no Linux knowledge, and takes you step by step through what you need to know to get the job done.
Get Linux up and running quickly Master basic operations and tackle more advanced tasks Get up to date on the recent changes to Linux server system management Bring Linux to the cloud using Openstack and Cloudforms Simplified Linux administration through the Cockpit Web Interface Automated Linux Deployment with Ansible Learn to navigate Linux with Amazon (AWS), Google (GCE), and Microsofr Azure Cloud services 
 is the one resource you need, and provides the hands-on training that gets you on track in a flash.

Linux Bible — читать онлайн ознакомительный отрывок

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Linux Bible», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

In the next example, the trcommand is used on a list of filenames to rename any files in that list so that any tabs or spaces (as indicated by the [:blank:]option) contained in a filename are translated into underscores. Try running the following code in a test directory:

for file in * ; do f=`echo $file | tr [:blank:] [_]` [ "$file" = "$f" ] || mv -i -- "$file" "$f" done

The stream editor (sed)

The sedcommand is a simple scriptable editor, so it can perform only simple edits, such as removing lines that have text matching a certain pattern, replacing one pattern of characters with another, and so on. To get a better idea of how sedscripts work, there's no substitute for the online documentation, but here are some examples of common uses.

You can use the sedcommand essentially to do what I did earlier with the grepexample: search the /etc/passwdfile for the word home. Here the sedcommand searches the entire /etc/passwdfile, searches for the word home, and prints any line containing the word home:

$ sed -n '/home/p' /etc/passwd chris:x:1000:1000:Chris Negus:/home/chris:/bin/bash joe:x:1001:1001:Joe Smith:/home/joe:/bin/bash

In this next example, sedsearches the file somefile.txtand replaces every instance of the string Macwith Linux. Notice that the letter gis needed at the end of the substitution command to cause every occurrence of Macon each line to be changed to Linux. (Otherwise, only the first instance of Macon each line is changed.) The output is then sent to the fixed_file.txtfile. The output from sedgoes to stdout, so this command redirects the output to a file for safekeeping.

$ sed 's/Mac/Linux/g' somefile.txt > fixed_file.txt

You can get the same result using a pipe:

$ cat somefile.txt | sed 's/Mac/Linux/g' > fixed_file.txt

By searching for a pattern and replacing it with a null pattern, you delete the original pattern. This example searches the contents of the somefile.txtfile and replaces extra blank spaces at the end of each line ( s/ *$) with nothing ( //). Results go to the fixed_file.txtfile.

$ cat somefile.txt | sed 's/ *$//' > fixed_file.txt

Using simple shell scripts

Sometimes, the simplest of scripts can be the most useful. If you type the same sequence of commands repetitively, it makes sense to store those commands (once!) in a file. The following sections offer a couple of simple, but useful, shell scripts.

Telephone list

This idea has been handed down from generation to generation of old UNIX hacks. It's really quite simple, but it employs several of the concepts just introduced.

#!/bin/bash # (@)/ph # A very simple telephone list # Type "ph new name number" to add to the list, or # just type "ph name" to get a phone number PHONELIST=~/.phonelist.txt # If no command line parameters ($#), there # is a problem, so ask what they're talking about. if [ $# -lt 1 ] ; then echo "Whose phone number did you want? " exit 1 fi # Did you want to add a new phone number? if [ $1 = "new" ] ; then shift echo $*>> $PHONELIST echo $* added to database exit 0 fi # Nope. But does the file have anything in it yet? # This might be our first time using it, after all. if [ ! -s $PHONELIST ] ; then echo "No names in the phone list yet! " exit 1 else grep -i -q "$*" $PHONELIST # Quietly search the file if [ $? -ne 0 ] ; then # Did we find anything? echo "Sorry, that name was not found in the phone list" exit 1 else grep -i "$*" $PHONELIST fi fi exit 0

So, if you created the telephone list file as phin your current directory, you could type the following from the shell to try out your phscript:

$ chmod 755 ph $ ./ph new "Mary Jones" 608-555-1212 Mary Jones 608-555-1212 added to database $ ./ph Mary Mary Jones 608-555-1212

The chmodcommand makes the phscript executable. The ./phcommand runs the phcommand from the current directory with the newoption. This adds Mary Jones as the name and 608-555-1212 as the phone number to the database ( $HOME/.phonelist.txt). The next phcommand searches the database for the name Mary and displays the phone entry for Mary. If the script works, add it to a directory in your path (such as $HOME/bin).

Backup script

Because nothing works forever and mistakes happen, backups are just a fact of life when dealing with computer data. This simple script backs up all of the data in the home directories of all of the users on your Fedora or RHEL system.

#!/bin/bash # (@)/my_backup # A very simple backup script # # Change the TAPE device to match your system. # Check /var/log/messages to determine your tape device. TAPE=/dev/rft0 # Rewind the tape device $TAPE mt $TAPE rew # Get a list of home directories HOMES=`grep /home /etc/passwd | cut -f6 -d':'` # Back up the data in those directories tar cvf $TAPE $HOMES # Rewind and eject the tape. mt $TAPE rewoffl

Summary

Writing shell scripts gives you the opportunity to automate many of your most common system administration tasks. This chapter covered common commands and functions that you can use in scripting with the bash shell. It also provided some concrete examples of scripts for doing backups and other procedures.

In the next chapter, you transition from learning about user features into examining system administration topics. Chapter 8, “Learning System Administration,” covers how to become the root user, as well as how to use administrative commands, monitor log files, and work with configuration files.

Exercises

Use these exercises to test your knowledge of writing simple shell scripts. These tasks assume you are running a Fedora or Red Hat Enterprise Linux system (although some tasks work on other Linux systems as well). If you are stuck, solutions to the tasks are shown in Appendix B(although in Linux, there are often multiple ways to complete a task).

1 Create a script in your $HOME/bin directory called myownscript. When the script runs, it should output information that appears as follows: Today is Sat Jan 4 15:45:04 EST 2020. You are in /home/joe and your host is abc.example.com.Of course, you need to read in your current date/time, current working directory, and hostname. Also, include comments about what the script does and indicate that the script should run with the /bin/bash shell.

2 Create a script that reads in three positional parameters from the command line, assigns those parameters to variables named ONE, TWO, and THREE, respectively, and outputs that information in the following format: There are X parameters that include Y. The first is A, the second is B, the third is C.Replace X with the number of parameters and Y with all parameters entered. Then replace A with the contents of variable ONE, B with variable TWO, and C with variable THREE.

3 Create a script that prompts users for the name of the street and town where they grew up. Assign town and street to variables called mytown and mystreet, and output them with a sentence that reads as shown below (of course, $mystreet and $mytown will appear with the actual town and street the user enters): The street I grew up on was $mystreet and the town was $mytown

4 Create a script called myos that asks the user, “What is your favorite operating system?” Output an insulting sentence if the user types “Windows” or “Mac.” Respond “Great choice!” if the user types “Linux.” For anything else, say “Is an operating system?”

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Linux Bible»

Представляем Вашему вниманию похожие книги на «Linux Bible» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Linux Bible»

Обсуждение, отзывы о книге «Linux Bible» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x