Working with Strings and Numbers
# CHAPTER 4
Working with Strings and Numbers
1. Introduction
By default, the Bash shell is not a mathematician; it is a text processor. When you typex=5+5 in Bash, the variable x does not equal 10. It literally equals the text string "5+5". To build complex automation tools—like calculating disk usage percentages, incrementing loop counters, or parsing specific letters out of a massive log file—you must explicitly force Bash to perform arithmetic, and you must learn the arcane art of string manipulation. In this chapter, we will master the techniques to slice, count, and concatenate text strings, and we will unlock the mathematical engine of the shell using the double parentheses (( )) and the expr command.
2. Learning Objectives
By the end of this chapter, you will be able to:- Concatenate multiple string variables into a single output.
-
Calculate the character length of a string using
${#VAR}.
- Extract specific sub-strings (slicing) from a larger variable.
- Perform basic integer arithmetic (addition, subtraction, multiplication).
-
Utilize the
expr,let, and Double Parentheses(( ))mathematical syntax.
3. String Manipulation
As a Linux administrator, you will constantly parse text (like extracting an IP address from a log entry).1. Concatenation (Joining Strings): Joining strings in Bash is incredibly easy. You just smash the variables together inside double quotes.
2. Finding String Length:
If you need to validate that a user's password is at least 8 characters long, you must count the characters. Place a Hash (#) inside the curly braces.
3. Substring Extraction (Slicing):
You can cut a specific chunk of text out of a variable.
*Syntax:* ${VARIABLE:Starting_Position:Length}
*(Note: Bash starts counting at 0, not 1).*
4. Arithmetic Operations (Math in Bash)
As mentioned,MATH=5+5 fails. There are three ways to force Bash to do math.
Method 1: The Modern Way (( ))
This is the standard, cleanest way to do math in modern Bash. The double parentheses instruct the shell to treat everything inside as numbers.
Method 2: The let Command
let is a built-in command that evaluates arithmetic expressions.
*Crucially, let allows you to increment counters easily without the $ symbol:*
Method 3: The Ancient expr Command
You will see expr in older, legacy scripts. It is an external program, so it is slower than the double parentheses.
*Warning: expr requires strict spaces around the mathematical operators!*
5. The Float Problem (Decimals)
Here is a massive limitation of Bash: Bash only understands Integers (whole numbers). If you typeecho $(( 10 / 3 )), Bash will output 3. It throws away the decimal remainder.
If you need precise decimal math (like calculating exactly 99.9% uptime), you must pipe the equation into an external calculator tool called bc (Basic Calculator).
6. Diagrams/Visual Suggestions
*Visual Concept: String Slicing Index* Create a visual grid displaying the wordU B U N T U.
Below each letter, place its index number starting from zero: 0 1 2 3 4 5.
Show the code ${OS:2:3}.
Draw a bounding box starting at index 2 (U) and spanning 3 blocks wide (U N T).
This visual grid is universally the best way to teach zero-indexed string slicing.
7. Best Practices
-
Use
$(( ))exclusively: Whileexprandletare historically important,$(( ))is POSIX compliant, runs faster because it is built directly into the shell, and is significantly easier to read. Standardize your scripts by using double parentheses for all integer math.
8. Common Mistakes
-
Multiplication Syntax in
expr: If you are forced to useexprfor multiplication, typingexpr 5 * 5will crash the script. Why? Because Bash sees the asterisk (*) and assumes it is the "Wildcard" character used to list files in a directory! You must "escape" the asterisk with a backslash so Bash treats it as a math symbol:expr 5 \* 5. *(This is another reason to use$(( ))instead).*
9. Mini Project: The System Storage Calculator
Let's build a script that does math to calculate storage quotas.-
1.
nano quota.sh
- 2. Write the code:
-
3.
chmod +x quota.sh
-
4.
Run it:
./quota.sh. You just built a custom mathematical monitoring tool!
10. Practice Exercises
-
1.
Given the variable
IP="192.168.1.100", write the exact Bash syntax to output the total number of characters in that string.
-
2.
Why does the command
RESULT=100/5fail to assign the number20to the variable? What doesRESULTactually equal in this scenario?
11. MCQs with Answers
A Bash script must calculate the division of 10 by 3 and return a precise decimal output of 3.33. Because Bash only handles integers natively, which external command-line utility must be utilized to achieve this decimal precision?
You have a variable named DATE="2026-10-31". Which substring extraction syntax will correctly capture only the 4-digit year?
12. Interview Questions
-
Q: You are auditing a legacy Bash script and see the command
TOTAL=$(expr $A * $B). The script constantly crashes on this specific line. Explain the mechanical conflict between the multiplication operator and the Bash shell, and how you would fix the syntax.
-
Q: Explain the paradigm difference between how a language like Python handles the assignment
x=5versus how the Bash shell handles the assignmentx=5. How does this dictate the necessity of the$(( ))syntax?
-
Q: A developer wants to extract the last 4 digits of a dynamically generated 16-character string variable named
TOKEN. Walk me through the mathematical slicing syntax required to achieve this.
13. FAQs
Q: Can I do math with variables, or just hardcoded numbers? A: You can absolutely use variables! In fact, inside the$(( )) brackets, you don't even need to use the $ symbol for variables. Bash is smart enough to know they are variables. Both RESULT=$(( $A + $B )) and RESULT=$(( A + B )) work perfectly.
14. Summary
In Chapter 4, we forced the text-based Bash shell to perform mathematical computation. We mastered string manipulation, concatenating dynamic outputs, calculating lengths with${#VAR}, and executing precise zero-indexed substring slicing. We addressed the shell's inherent inability to process raw mathematical symbols by embracing the Double Parentheses $(( )) syntax for robust integer arithmetic. We acknowledged the historical context of expr and let, and finally, we deployed the external bc utility to bridge the gap in Bash's inability to calculate floating-point decimals.