Skip to main content
Bash Scripting – Complete Beginner to Advanced Guide
CHAPTER 04 Intermediate

Working with Strings and Numbers

Updated: May 16, 2026
25 min read

# 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 type x=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.

bash
1234
FIRST="Linux"
SECOND="Server"
COMBINED="$FIRST $SECOND"
echo $COMBINED  # Output: Linux Server

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.

bash
123
PASSWORD="MySecretPassword"
echo "The password length is: ${#PASSWORD}"
# Output: The password length is: 16

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).*

bash
1234
PHONE="555-867-5309"
# Extract 3 characters, starting at position 4
PREFIX=${PHONE:4:3}
echo $PREFIX  # Output: 867

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.

bash
1234567891011
#!/bin/bash
NUM1=10
NUM2=5

# Calculate and store the result
RESULT=$(( NUM1 + NUM2 ))
echo "Addition: $RESULT"

# Multiplication
RESULT=$(( NUM1 * NUM2 ))
echo "Multiplication: $RESULT"

Method 2: The let Command let is a built-in command that evaluates arithmetic expressions.

bash
12
let "RESULT = 10 + 20"
echo $RESULT

*Crucially, let allows you to increment counters easily without the $ symbol:*

bash
1
let COUNTER++  # Adds 1 to the counter

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!*

bash
12345
# Correct
RESULT=$(expr 10 + 5)

# Incorrect (Will output the literal string "10+5")
RESULT=$(expr 10+5)

5. The Float Problem (Decimals)

Here is a massive limitation of Bash: Bash only understands Integers (whole numbers). If you type echo $(( 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).
bash
123
# Scale=2 tells bc to provide 2 decimal places
echo "scale=2; 10 / 3" | bc
# Output: 3.33

6. Diagrams/Visual Suggestions

*Visual Concept: String Slicing Index* Create a visual grid displaying the word U 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: While expr and let are 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 use expr for multiplication, typing expr 5 * 5 will 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. 1. nano quota.sh
  1. 2. Write the code:
bash
1234567891011121314151617
#!/bin/bash

# Define variables in Gigabytes
TOTAL_DRIVE=500
USED_SPACE=350

# Calculate remaining space
FREE_SPACE=$(( TOTAL_DRIVE - USED_SPACE ))

# Calculate basic percentage (Integer only!)
PERCENT_USED=$(( (USED_SPACE * 100) / TOTAL_DRIVE ))

echo "Storage Report:"
echo "----------------"
echo "Total Capacity: ${TOTAL_DRIVE}GB"
echo "Free Space: ${FREE_SPACE}GB"
echo "Usage: ${PERCENT_USED}% Full"
  1. 3. chmod +x quota.sh
  1. 4. Run it: ./quota.sh. You just built a custom mathematical monitoring tool!

10. Practice Exercises

  1. 1. Given the variable IP="192.168.1.100", write the exact Bash syntax to output the total number of characters in that string.
  1. 2. Why does the command RESULT=100/5 fail to assign the number 20 to the variable? What does RESULT actually equal in this scenario?

11. MCQs with Answers

Question 1

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?

Question 2

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=5 versus how the Bash shell handles the assignment x=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.

15. Next Chapter Recommendation

Your scripts can calculate data, but they lack logic. They run straight from top to bottom. We need to teach the script how to make decisions based on the data it calculates. Proceed to Chapter 5: Conditional Statements.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·