Let's see a few examples of how to compare Strings in a Bash Script,
Example 1: using [ ]
#!/bin/bash
name1="Mike"
name2="Mikey"
if [ "$name1" = "$name2" ]; then
echo "Both names are the same."
else
echo "Both names are not the same."
fi
Example 2: using (( ))
#!/bin/bash
name1="Mike"
name2="Mikey"
if (( "$name1" == "$name2" )); then
echo "Both names are the same."
else
echo "Both names are not the same."
fi
Example 2: using [[ ]]
#!/bin/bash
name1="Mike"
name2="Mikey"
if [[ "$name1" == "$name2" ]]; then
echo "Both names are the same."
else
echo "Both names are not the same."
fi
Comare String Methods | Explanation |
---|---|
[ "$string1" = "$string2" ] |
To check if two strings are equal. |
[ "$string1" != "$string2" ] |
To check if two strings are not equal. |
(( "$string1" == "$string2" )) |
To perform a numeric comparison for equality (0) or inequality (1). |
[[ "$string1" == "$string2" ]] |
To perform pattern matching and string comparison. |

-
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Bash,
- Bash Hello World! Script Tutorial
- How to run bash command in background
- How to create new user account in Windows bash
- How to Compare Strings in Bash
- Bash: Allow Command to Fail without exiting Script
- Fix bash: script.sh: Permission denied Error
- Bash getopts Command Example
- How to fix bash ping command not found error
- How to add NewLine Character in Bash Script String
- How to Echo Bash Command to a File
- Bash Command to Find String in a File
- How to open new Terminal using Bash Command
- Bash How to Save Output of a Command to a Variable
- Download a SSL Certificate from a URL in Terminal
- Bash Command to Check IP Address
- Know Bash shell version command
- Bash Command To Check If File Exists
- How to run a Command in Bash Script
- How to Compare two Files in Bash Shell
- How to check if a variable is set in Bash Script or Not
- Convert String from uppercase to lowercase in Bash
- How to see Created Accessed Modified and Changed dates of a file using bash terminal command
- Bash Command To Get Current Time
- Bash command to List Files
- Fix: bash: syntax error near unexpected token
More Posts:
- How to Open Finder using Mac Terminal - MacOS
- Android Studio emulator/Device logCat logs not displayed - Android-Studio
- How to embed web page in SharePoint - SharePoint
- How to know the Safari Version on Mac - MacOS
- Convert Java Array to ArrayList Code Example - Java
- How to show End of Line Characters in File using Notepad++ - NotepadPlusPlus
- The selected device is incompatible : Android Studio - Android-Studio
- Bash Command to Find String in a File - Bash