Learn how to effectively utilize the Bash shell in your programming. This refreshed and expanded third edition has been updated to Bash 5.2, and many scripts have been rewritten to make them more idiomatically Bash, taking better advantage of features specific to Bash. It is easy to read, understand, and will teach you how to get to grips with Bash programming without drowning you in pages and pages of syntax.
Using this book you will be able to use the shell efficiently, make scripts run faster using expansion and external commands, and understand how to overcome many common mistakes that cause scripts to fail. This book is perfect for all beginning Linux and Unix system administrators who want to be in full control of their systems, and really get to grips with Bash programming.
The Bash shell is a complete programming language, not merely a glue to combine external Linux commands. By taking full advantage of Shell internals, Shell programs can perform as snappily as utilities written in C or other compiled languages. And you will see how, without assuming UNIX lore, you can write professional Bash programs through standard programming techniques.
What You'll Learn
- Use the Bash shell to write utilities and accomplish most programming tasks
- Replace many external commands with shell parameter expansion making scripts very fast
- Avoid many common mistakes that cause scripts to fail
- See how Bash’s read line and history libraries can save typing when getting user input
- Build shell scripts that get information from the Web
Who This Book Is For
Developers, programmers, and open source enthusiasts who want to write scripts using Bash on multiple platforms
Author(s): Jayant Varma
Edition: 3
Publisher: Apress
Year: 2023
Language: English
Commentary: Publisher PDF | Published: 22 November 2023
Pages: xxi, 305
City: Berkeley, CA
Tags: Bash; GNU; UNIX; Shell Script; Linux; GNU/Linux; Scripting; Open Source; Mac OSX; Terminal
Table of Contents
About the Authors
About the Technical Reviewer
Acknowledgments
Chapter 1: Hello, World: Your First Shell Program
What Is a Shell Script?
The Hello World Code
The Hello World Program File
Naming the Script File
Selecting a Directory for the Script
Creating the File and Running the Script
Choosing and Using a Text Editor
Building a Better “Hello, World!”
Summary
Commands
Concepts
Variables
Exercises
Chapter 2: Input, Output, and Throughput
Parameters and Variables
Positional Parameters
Special *@#0$?_!- Parameters
Variables
Arguments and Options
Why You Should Avoid echo
printf: Formatting and Printing Data
Escape Sequences
Format Specifiers
Width Specification
Printing to a Variable
Line Continuation
Standard Input/Output Streams and Redirection
Redirection: >, >>, and <
Reading Input
Pipelines
Command Substitution
Summary
Commands
Concepts
Exercises
Chapter 3: Looping and Branching
Exit Status
Testing an Expression
test, a.k.a. [ … ]
File Tests
Integer Tests
String Tests
[[ … ]]: Evaluate an Expression
Enhancements over Test
(( …)): Evaluate an Arithmetic Expression
Conditional Execution
if
Conditional Operators: && and ||
case
Looping
while
until
for
break
continue
Summary
Commands
Concepts
Exercises
Chapter 4: Command-Line Parsing and Expansion
Quoting
Brace Expansion
Tilde Expansion
Parameter and Variable Expansion
Arithmetic Expansion
Command Substitution
Word Splitting
Pathname Expansion
Process Substitution
Parsing Options
Summary
Commands
Exercises
Chapter 5: Parameters and Variables
The Naming of Variables
The Scope of a Variable: Can You See It from Here?
Shell Variables
Shell Variables
Parameter Expansion
Bourne Shell
${var:-default} and ${var-default}: Use Default Values
${var:+alternate} and ${var+alternate}: Use Alternate Values
${var:=default} and ${var=default}: Assign Default Values
${var:?message} and ${var?message}: Display Error Message If Empty or Unset
POSIX Shell
${#var}: Length of Variable’s Contents
${var%PATTERN}: Remove the Shortest Match from the End
${var%%PATTERN}: Remove the Longest Match from the End
${var#PATTERN}: Remove the Shortest Match from the Beginning
${var##PATTERN}: Remove the Longest Match from the Beginning
bash
${var//PATTERN/STRING}: Replace All Instances of PATTERN with STRING
${var:OFFSET:LENGTH}: Return a Substring of $var
${!var}: Indirect Reference
bash-4.0
${var^PATTERN}: Convert to Uppercase
${var,PATTERN}: Convert to Lowercase
Positional Parameters
Arrays
Integer-Indexed Arrays
Displaying Arrays
Assigning Array Elements
Associative Arrays
Summary
Commands
Concepts
Exercises
Chapter 6: Shell Functions
Definition Syntax
Compound Commands
Getting Results
Set Different Exit Codes
Print the Result
Place Results in One or More Variables
Function Libraries
Using Functions from Libraries
Sample Script
Summary
Commands
Exercises
Chapter 7: String Manipulation
Concatenation
Repeat Character to a Given Length
Processing Character by Character
Reversal
Case Conversion
Comparing Contents Without Regard to Case
Check for Valid Variable Name
Insert One String into Another
Examples
Overlay
Examples
Trim Unwanted Characters
Examples
Index
Summary
Commands
Functions
Exercises
Chapter 8: File Operations and Commands
Reading a File
External Commands
cat
head
touch
ls
cut
wc
Regular Expressions
grep
sed
awk
File Name Expansion Options
nullglob
failglob
dotglob
extglob
?(pattern-list)
*(pattern-list)
@(pattern-list)
+(pattern-list)
!(pattern-list)
nocaseglob
globstar
Summary
Shell Options
External Commands
Exercises
Chapter 9: Reserved Words and Built-In Commands
help, Display Information About Built-In Commands
time, Print Time Taken for Execution of a Command
read, Read a Line from an Input Stream
-r, Read Backslashes Literally
-e, Get Input with the readline Library
-a, Read Words into an Array
-d DELIM, Read Until DELIM Instead of a Newline
-n NUM, Read a Maximum of NUM Characters
-s, Do Not Echo Input Coming from a Terminal
-p PROMPT:, Output PROMPT Without a Trailing Newline
-t TIMEOUT, Only Wait TIMEOUT Seconds for Complete Input
-u FD: Read from File Descriptor FD Instead of the Standard Input
-i TEXT, Use TEXT As the Initial Text for Readline
eval, Expand Arguments and Execute the Resulting Command
Poor Man’s Arrays
Setting Multiple Variables from One Command
type, Display Information About Commands
builtin, Execute a Built-In Command
command, Execute a Command or Display Information About Commands
pwd, Print the Current Working Directory
unalias, Remove One or More Aliases
Deprecated Built-Ins
Dynamically Loadable Built-Ins
Summary
Commands and Reserved Words
Deprecated Commands
Exercise
Chapter 10: Writing Bug-Free Scripts and Debugging the Rest
Prevention Is Better Than Cure
Structure Your Programs
Comments
Initialization of Variables
Function Definitions
Runtime Configuration and Options
Process Information
Document Your Code
Format Your Code Consistently
The K.I.S.S. Principle
Grouping Commands
Test As You Go
Debugging a Script
Summary
Exercises
Chapter 11: Programming for the Command Line
Manipulating the Directory Stack
cd
pd
cdm
dirs Built-In Command
menu
Filesystem Functions
l
lsr
cp, mv
md
Miscellaneous Functions
pr1
calc
Managing Man Pages
sman
sus
k
Games
The fifteen Puzzle
Summary
Exercises
Chapter 12: Runtime Configuration
Defining Variables
Command-Line Options and Arguments
Menus
Q&A Dialogue
Configuration Files
Scripts with Several Names
Environment Variables
All Together Now
Script Information
Default Configuration
Screen Variables
Function Definitions
Function: die
Function: menu
The Upload Settings Menu
Function: qa
Function: print_config
Function: readline
Parse Command-Line Options
Bits and Pieces
Summary
Exercises
Chapter 13: Data Processing
Arrays
Holes in an Indexed Array
Using an Array for Sorting
Insertion Sort Function
Searching an Array
Reading an Array into Memory
Two-Dimensional Grids
Working with Single-String Grids
Function: initgrid
Function: gridindex
Function: putgrid
Function: getgrid
Function: showgrid
Function: rshowgrid
Two-Dimensional Grids Using Arrays
Function: initagrid
Function: putagrid
Function: getagrid
Function: showagrid
Function: rshowagrid
Data File Formats
Line-Based Records
Delimiter-Separated Values
Fixed-Length Fields
Block File Formats
Summary
Exercises
Chapter 14: Scripting the Screen
Teletypewriter vs. Canvas
Stretching the Canvas
Control Sequence Introducer
Priming the Canvas
Moving the Cursor
Changing Rendition Modes and Colors
Placing a Block of Text on the Screen
Scrolling Text
Rolling Dice
Summary
Exercises
Chapter 15: Entry-Level Programming
Single-Key Entry
Function Library, key-funcs
History in Scripts
Sanity Checking
Form Entry
Reading the Mouse
Summary
Exercises
Appendix A: Shell Variables
Index