Bash – Check if string starts with specific prefix
To check if a string starts with specific prefix string in Bash scripting, you can use the following condition.
</>
Copy
$string1 == $prefix*
where string1
is a whole string, and prefix
is a prefix string.
If the string string1
starts with prefix
string, then the above expression returns true, else it returns false.
Example
In the following script, we take two strings in string1
and prefix
, and check if string string1
starts with the prefix
.
example.sh
</>
Copy
#! /bin/bash
string1="hello world"
prefix="hello"
if [[ $string1 == $prefix* ]]; then
echo "String starts with prefix"
else
echo "String does not start with prefix"
fi
Output
sh-3.2# ./example.sh
String starts with prefix
References
Conclusion
In this Bash Tutorial, we learned how to check if a string starts with a specific prefix string.