Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Linux Command Line and Shell Scripting Bible - Third Edition

You're reading from  Linux Command Line and Shell Scripting Bible - Third Edition

Product type Book
Published in Jan 2015
Publisher Wiley
ISBN-13 9781118983843
Pages 816 pages
Edition 3rd Edition
Languages
Authors (2):
Richard Blum Richard Blum
Profile icon Richard Blum
Christine Bresnahan Christine Bresnahan
Profile icon Christine Bresnahan
View More author details

Table of Contents (34) Chapters

1. Introduction 2. Part I: The Linux Command Line
3. Chapter 1: Starting with Linux Shells 4. Chapter 2: Getting to the Shell 5. Chapter 3: Basic bash Shell Commands 6. Chapter 4: More bash Shell Commands 7. Chapter 5: Understanding the Shell 8. Chapter 6: Using Linux Environment Variables 9. Chapter 7: Understanding Linux File Permissions 10. Chapter 8: Managing Filesystems 11. Chapter 9: Installing Software 12. Chapter 10: Working with Editors 13. Part II: Shell Scripting Basics
14. Chapter 11: Basic Script Building 15. Chapter 12: Using Structured Commands 16. Chapter 13: More Structured Commands 17. Chapter 14: Handling User Input 18. Chapter 15: Presenting Data 19. Chapter 16: Script Control 20. Part III: Advanced Shell Scripting
21. Chapter 17: Creating Functions 22. Chapter 18: Writing Scripts for Graphical Desktops 23. Chapter 19: Introducing sed and gawk 24. Chapter 20: Regular Expressions 25. Chapter 21: Advanced sed 26. Chapter 22: Advanced gawk 27. Chapter 23: Working with Alternative Shells 28. Part IV: Creating Practical Scripts
29. Chapter 24: Writing Simple Script Utilities 30. Chapter 25: Producing Scripts for Database, Web, and E-Mail 31. Chapter 26: Creating Fun Little Shell Scripts 32. End User License Agreement
Appendix A: Quick Guide to bash Commands 1. Appendix B: Quick Guide to sed and gawk

Chapter 11
Basic Script Building

Using Multiple Commands

So far you've seen how to use the command line interface (CLI) prompt of the shell to enter commands and view the command results. The key to shell scripts is the ability to enter multiple commands and process the results from each command, even possibly passing the results of one command to another. The shell allows you to chain commands together into a single step.

If you want to run two commands together, you can enter them on the same prompt line, separated with a semicolon:

$ date ; who
Mon Feb 21 15:36:09 EST 2014
Christine tty2         2014-02-21 15:26
Samantha tty3         2014-02-21 15:26
Timothy  tty1         2014-02-21 15:26
user     tty7         2014-02-19 14:03 (:0)
user     pts/0        2014-02-21 15:21 (:0.0)
$

Congratulations, you just wrote a shell script! This simple script uses just two bash shell commands. The date command runs first, displaying the current date and time, followed by the output of the who command, showing who is currently...

Creating a Script File

To place shell commands in a text file, first you need to use a text editor (see Chapter 10) to create a file and then enter the commands into the file.

When creating a shell script file, you must specify the shell you are using in the first line of the file. Here's the format for this:

#!/bin/bash

In a normal shell script line, the pound sign (#) is used as a comment line. A comment line in a shell script isn't processed by the shell. However, the first line of a shell script file is a special case, and the pound sign followed by the exclamation point tells the shell what shell to run the script under (yes, you can be using a bash shell and run your script using another shell).

After indicating the shell, commands are entered onto each line of the file, followed by a carriage return. As mentioned, comments can be added by using the pound sign. An example looks like this:

#!/bin/bash
# This script displays the date and who's logged on
date
who

And...

Displaying Messages

Most shell commands produce their own output, which is displayed on the console monitor where the script is running. Many times, however, you will want to add your own text messages to help the script user know what is happening within the script. You can do this with the echo command. The echo command can display a simple text string if you add the string following the command:

$ echo This is a test
This is a test
$

Notice that by default you don't need to use quotes to delineate the string you're displaying. However, sometimes this can get tricky if you are using quotes within your string:

$ echo Let's see if this'll work
Lets see if thisll work
$

The echo command uses either double or single quotes to delineate text strings. If you use them within your string, you need to use one type of quote within the text and the other type to delineate the string:

$ echo "This is a test to see if you're paying attention"
This is a test to...

Using Variables

Just running individual commands from the shell script is useful, but this has its limitations. Often, you'll want to incorporate other data in your shell commands to process information. You can do this by using variables. Variables allow you to temporarily store information within the shell script for use with other commands in the script. This section shows how to use variables in your shell scripts.

Environment variables

You've already seen one type of Linux variable in action. Chapter 6 described the environment variables available in the Linux system. You can access these values from your shell scripts as well.

The shell maintains environment variables that track specific system information, such as the name of the system, the name of the user logged in to the system, the user's system ID (called UID), the default home directory of the user, and the search path used by the shell to find programs. You can display a complete list of active environment...

Redirecting Input and Output

Sometimes, you want to save the output from a command instead of just having it displayed on the monitor. The bash shell provides a few different operators that allow you to redirect the output of a command to an alternative location (such as a file). Redirection can be used for input as well as output, redirecting a file to a command for input. This section describes what you need to do to use redirection in your shell scripts.

Output redirection

The most basic type of redirection is sending output from a command to a file. The bash shell uses the greater-than symbol (>) for this:

command > outputfile

Anything that would appear on the monitor from the command instead is stored in the output file specified:

$ date > test6
$ ls -l test6
-rw-r--r--    1 user     user           29 Feb 10 17:56 test6
$ cat test6
Thu Feb 10 17:56:58 EDT 2014
$

The redirect operator created the file test6 (using the default umask settings) and redirected the output from...

Pipes

Sometimes, you need to send the output of one command to the input of another command. This is possible using redirection, but somewhat clunky:

$ rpm -qa > rpm.list
$ sort < rpm.list
abrt-1.1.14-1.fc14.i686
abrt-addon-ccpp-1.1.14-1.fc14.i686
abrt-addon-kerneloops-1.1.14-1.fc14.i686
abrt-addon-python-1.1.14-1.fc14.i686
abrt-desktop-1.1.14-1.fc14.i686
abrt-gui-1.1.14-1.fc14.i686
abrt-libs-1.1.14-1.fc14.i686
abrt-plugin-bugzilla-1.1.14-1.fc14.i686
abrt-plugin-logger-1.1.14-1.fc14.i686
abrt-plugin-runapp-1.1.14-1.fc14.i686
acl-2.2.49-8.fc14.i686
[...]

The rpm command manages the software packages installed on systems using the Red Hat Package Management system (RPM), such as the Fedora system as shown. When used with the -qa parameters, it produces a list of the existing packages installed, but not necessarily in any specific order. If you're looking for a specific package or group of packages, it can be difficult to find it using the output of the rpm command.

Using the...

Performing Math

Another feature crucial to any programming language is the ability to manipulate numbers. Unfortunately, for shell scripts this process is a bit awkward. There are two different ways to perform mathematical operations in your shell scripts.

The expr command

Originally, the Bourne shell provided a special command that was used for processing mathematical equations. The expr command allowed the processing of equations from the command line, but it is extremely clunky:

$ expr 1 + 5
6

The expr command recognizes a few different mathematical and string operators, shown in Table 11.1.

Table 11.1 The expr Command Operators

Operator Description
ARG1 | ARG2 Returns ARG1 if neither argument is null or zero; otherwise, returns ARG2
ARG1 & ARG2 Returns ARG1 if neither argument is null or zero; otherwise, returns 0
ARG1 < ARG2 Returns 1 if ARG1 is less than ARG2; otherwise, returns 0
ARG1 <= ARG2 Returns 1 if ARG1 is less than or equal to ARG2; otherwise, returns...

Exiting the Script

So far in our sample scripts, we terminated things pretty abruptly. When we were finished with our last command, we just ended the script. There's a more elegant way of completing things available to us.

Every command that runs in the shell uses an exit status to indicate to the shell that it's finished processing. The exit status is an integer value between 0 and 255 that's passed by the command to the shell when the command finishes running. You can capture this value and use it in your scripts.

Checking the exit status

Linux provides the $? special variable that holds the exit status value from the last command that executed. You must view or use the $? variable immediately after the command you want to check. It changes values to the exit status of the last command executed by the shell:

$ date
Sat Jan 15 10:01:30 EDT 2014
$ echo $?
0
$

By convention, the exit status of a command that successfully completes is zero. If a command completes with an...

Summary

The bash shell script allows you to string commands together into a script. The most basic way to create a script is to separate multiple commands on the command line using a semicolon. The shell executes each command in order, displaying the output of each command on the monitor.

You can also create a shell script file, placing multiple commands in the file for the shell to execute in order. The shell script file must define the shell used to run the script. This is done in the first line of the script file, using the #! symbol, followed by the full path of the shell.

Within the shell script you can reference environment variable values by using a dollar sign in front of the variable. You can also define your own variables for use within the script, and assign values and even the output of a command by using the backtick character or the $() format. The variable value can be used within the script by placing a dollar sign in front of the variable name.

The bash shell allows you...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Linux Command Line and Shell Scripting Bible - Third Edition
Published in: Jan 2015 Publisher: Wiley ISBN-13: 9781118983843
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}