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

Substring Extraction

Substring extraction is like cutting a slice out of a long ribbon. You say where to start cutting and how long a piece you want.

In this page:

  1. Substring Extraction
Syntax
bash
${variable:start:length}
${variable:start}

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}"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using ${str:1:3} and expecting 3 to be the end index, when it is the length.
  2. Forgetting that offsets start at 0.
  3. Using a negative offset without a space, as in ${str:-3}, which means a default value; write ${str: -3}.

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.