Skip to Content
Learning the bash Shell, Second Edition
book

Learning the bash Shell, Second Edition

by Cameron Newham, Bill Rosenblatt
January 1998
Beginner
336 pages
10h 6m
English
O'Reilly Media, Inc.
Content preview from Learning the bash Shell, Second Edition

String Operators

The curly-bracket syntax allows for the shell’s string operators. String operators allow you to manipulate values of variables in various useful ways without having to write full-blown programs or resort to external UNIX utilities. You can do a lot with string-handling operators even if you haven’t yet mastered the programming features we’ll see in later chapters.

In particular, string operators let you do the following:

  • Ensure that variables exist (i.e., are defined and have non-null values)

  • Set default values for variables

  • Catch errors that result from variables not being set

  • Remove portions of variables’ values that match patterns

Syntax of String Operators

The basic idea behind the syntax of string operators is that special characters that denote operations are inserted between the variable’s name and the right curly bracket. Any argument that the operator may need is inserted to the operator’s right.

The first group of string-handling operators tests for the existence of variables and allows substitutions of default values under certain conditions. These are listed in Table 4.1. [51]

Table 4-1. Substitution Operators

Operator Substitution
$ { varname :- word }

If varname exists and isn’t null, return its value; otherwise return word.

Purpose:

Returning a default value if the variable is undefined.

Example:

${count:-0} evaluates to 0 if count is undefined.

$ { varname := word}

If varname exists and isn’t null, return its value; otherwise set it to word

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning the bash Shell, 3rd Edition

Learning the bash Shell, 3rd Edition

Cameron Newham

Publisher Resources

ISBN: 1565923472Supplemental ContentCatalog PageErrata