This page has been tested on macOS Catalina and Ubuntu 18.04 & 20.04

⇦ Back

1 Concatenating

Joining two strings is a simple case of calling them one after another:

a=Hello
b=World
# Remember to use double quotation marks when there is a space
c="$a, $b"
echo $c
Hello, World

This is useful for things like units:

value=100
units=ms
output=$value$units
echo $output
100ms

and URLS:

website_name='facebook'
url="www.$website_name.com"
echo $url
www.facebook.com

and filepaths:

folder_name='Documents'
filepath="/Users/yourname/$folder_name/filename.sh"
echo $filepath
/Users/yourname/Documents/filename.sh

A shortcut for concatenation is to use addition (+=):

a="Hello"
a+=" World"
echo "${a}"
Hello World

2 Indexing

A string is indexed using the format ${string:position} or ${string:position:length}. Strings use zero-based indexing which means that the first character is actually referred to as the 0th character.

This means that, if given the following string:

str="0123456789"

You can extract one character by specifying its position and a length of 1:

echo "${str:0:1}"
echo "${str:1:1}"
echo "${str:2:1}"
0
1
2

You can extract all characters from a certain position onwards by leaving “length” blank:

echo "${str:4}"
456789

You can also index from the right-hand side of the string using a minus sign, although you need to include round brackets or a space:

echo "${str:(-4)}"
echo "${str: -4}"
6789
6789

3 Searching

Does a string contain a given substring?

str='Hello, World'
if [[ $str == *"World"* ]]
then
  echo 'String does contain "World"'
fi
String does contain "World"

⇦ Back