← Back to Bash Course | Chapter 5: Functions | Lesson 3 of 11

Substring Extraction

In this page:

  1. Substring Extraction

Substring Extraction

${variable:start:length} extracts a portion of a string starting at a given index (0-based) for a given number of characters. Omitting length extracts everything from start to the end. This is Bash's built-in equivalent of a substring function found in other languages.

Note: A negative start, like ${var: -3}, extracts from the end of the string (note the required space before the minus).

Example: Substring Extraction

bash
#!/bin/bash
text="Hello, Bash World!"
echo "${text:0:5}"
echo "${text:7:4}"
echo "${text:7}"

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.