0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Extract Substring in Bash: Simple Syntax and Examples

In Bash, you can extract a substring from a string using ${string:position:length}. Here, position is the start index (0-based), and length is how many characters to extract.
📐

Syntax

The basic syntax to extract a substring in Bash is:

  • ${string:position:length}

Where:

  • string is your original text.
  • position is the starting index (0-based).
  • length is the number of characters to extract (optional).

If length is omitted, the substring from position to the end of the string is returned.

bash
substring=${string:position:length}
💻

Example

This example shows how to extract a substring from a string variable in Bash. It extracts 5 characters starting from index 3.

bash
string="Hello, world!"
substring=${string:3:5}
echo "$substring"
Output
lo, w
⚠️

Common Pitfalls

Common mistakes include:

  • Using 1-based indexing instead of 0-based (Bash starts counting at 0).
  • Forgetting that length is optional and omitting it extracts till the end.
  • Trying to use substring extraction on unquoted variables which may cause word splitting.
bash
string="Example"
# Using 1-based indexing is not wrong, but remember it starts at 0
# This extracts characters starting at index 1 (second character)
echo "${string:1:3}"  # outputs 'xam'

# Correct: starts at 0 for first character
echo "${string:0:3}"  # outputs 'Exa'
Output
xam Exa
📊

Quick Reference

SyntaxDescription
${string:position}Extract substring from position to end
${string:position:length}Extract substring of length starting at position
position starts at 0Indexing is zero-based
length optionalIf omitted, extracts till end

Key Takeaways

Use ${string:position:length} to extract substrings in Bash with zero-based indexing.
Omitting length extracts substring from position to the end.
Always quote variables when using substring extraction to avoid word splitting.
Remember position starts at 0, not 1.
This method works in Bash and is simple for quick substring extraction.