Often you may want to use Bash to extract a string from between brackets.
You can use the following syntax to do so:
echo $my_string | cut -d "[" -f2 | cut -d "]" -f1
This particular example will extract the string from between the brackets in the variable named my_string.
Here is how this syntax works:
- echo $my_string: Display entire string from $my_string variable.
- cut -d “[” -f2: Extract second field from string, using left bracket as delimiter. This extracts all text to the right of the first bracket.
- cut -d “]” -f1: Extract second field from string, using right bracket as delimiter. This extracts all text to the left of the second bracket.
The following example shows how to use this syntax in practice.
Example: How to Extract String from Brackets in Bash
Suppose that we create a variable named my_string in Bash with the following text:
- I use [546AD] as my identification number
And suppose that we would like to extract only the string between the brackets to get:
- 546AD
We can use the following syntax to do so:
my_string="I use [546AD] as my identification number"
echo $my_string | cut -d "[" -f2 | cut -d "]" -f1
The following screenshot shows how to use this syntax in practice:

Notice that we’re able to extract the following text:
- 546AD
This represents only the string between the brackets.
We could also use the following syntax to save this text to a new variable named brack:
my_string="I use [546AD] as my identification number"
brack=$(echo $my_string | cut -d "[" -f2 | cut -d "]" -f1)
echo $brack
The following screenshot shows how to use this syntax in practice:

Notice that when we use the echo statement to view the brack variable we can see that it contains only the string between the brackets.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Extract Text Between Two Strings
Bash: How to Replace Multiple Characters in String
Bash: How to Replace All Occurrences of String in File
