In the next example, the tr
command 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 sed
command 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 sed
scripts work, there's no substitute for the online documentation, but here are some examples of common uses.
You can use the sed
command essentially to do what I did earlier with the grep
example: search the /etc/passwd
file for the word home
. Here the sed
command searches the entire /etc/passwd
file, 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, sed
searches the file somefile.txt
and replaces every instance of the string Mac
with Linux
. Notice that the letter g
is needed at the end of the substitution command to cause every occurrence of Mac
on each line to be changed to Linux
. (Otherwise, only the first instance of Mac
on each line is changed.) The output is then sent to the fixed_file.txt
file. The output from sed
goes 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.txt
file and replaces extra blank spaces at the end of each line ( s/ *$
) with nothing ( //
). Results go to the fixed_file.txt
file.
$ 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.
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 ph
in your current directory, you could type the following from the shell to try out your ph
script:
$ 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 chmod
command makes the ph
script executable. The ./ph
command runs the ph
command from the current directory with the new
option. This adds Mary Jones as the name and 608-555-1212 as the phone number to the database ( $HOME/.phonelist.txt
). The next ph
command 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
).
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
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.
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?”
Читать дальше