Substrings in Bash

Posted: 17th October 2010 by Tim in Bash
Tags: , , , , , , , ,

There are a number of ways to extract parts of a string in bash. If you know the position of the substring you’re looking for, then you can use the ${string:offset[:length]} syntax. This works by providing a string, an offset (or starting position – remember that the first letter is in position 0) and, optionally, a length. If the length is not specified then the rest of the string is returned. Unfortunately, you can’t use this syntax to get the end of a string unless you know it’s length. Giving a negative offset will return the whole string, and giving a negative length will throw an error.

For example:



echo "'$str'"
echo "'${str:0:3}'"
echo "'${str:3:2}'"
echo "'${str:10:2}'"
echo "'${str:2}'"
echo "'${str:-2:2}'"

will print out:


  1. Janos Kramar says:

    Actually what you’re saying about negative offsets isn’t true – in fact you can use a negative offset, but you have to make it an expression, eg 0-2.
    echo “‘${str:0-2}'” will print out ‘de’.