Compare string in BASH - JohnHau/mis GitHub Wiki

The need to compare strings in a Bash script is relatively common and can be used to check for certain conditions before proceeding on to the next part of a script. A string can be any sequence of characters. To test if two strings are the same, both strings must contain the exact same characters and in the same order. It could be a word or a whole sentence. For example, string one is equal to string one but is not equal to string two. Get the idea?

In this guide, we’ll show you how to compare strings in the Bash shell on a Linux system. We’ll show this in the context of a simple if/else Bash script so you can see how testing for this condition would work when developing scripts, but we’ll also show how this same comparison can be done in the command line terminal.

In this tutorial you will learn:

How to compare strings in Bash Example if/else Bash scripts that compare strings

Compare if two strings are equal You can open a terminal on your system and use some of these examples to get a feel for how Bash operators work when it comes to comparing strings.

You can use the following syntax to compare two strings.

$ [ "apples" = "apples" ] $ echo $? 0 The returned value of 0 means true. In other words, the strings match (as we can clearly see for ourselves).

image

image

image

image

image