Bash IF var contains a certain string

Hello

I am having trouble finding a way to check if a variable contains a certain string

what I want is something like that

if [ $variable contains "serach_text"]
then

fi

I know a cheap and easy way of doing this would be
but I was looking for other ways
if [ echo $variable | grep "search_text]
then

fi


Thanks for your time and help
LVL 2
jculkincysAsked:
Who is Participating?
 
ravenplCommented:
I already have showed that. Haven't I?

if [[ -n "$var" && $var == *answer* ]]
0
 
ravenplCommented:
if [ _$var = "_search text" ]; then
...
0
 
ravenplCommented:
posibly better
if [ "_$var" = "_search text" ]; then
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
jculkincysAuthor Commented:
Can you please explain a little what the underscore does?
0
 
jculkincysAuthor Commented:
Will your solution will let me know if the variable contains the search text or will it tell me if the variable is equal t the search text.
0
 
ravenplCommented:
> Can you please explain a little what the underscore does?
supresses error if $var is empty

> Will your solution will let me know if the variable contains the search text or will it tell me if the variable is equal t the search text.
Right - it checks for equality.

if [[ -n "$var" && $var == *searched\ text* ]]; then
0
 
jculkincysAuthor Commented:
Alright

Is there any easy way to check if the variable contains the search string

Here is a better example

$var = "ravenpl answer"
if [$var contains "answer"]
then
        give him the points and an A
gi
0
 
jculkincysAuthor Commented:
Oh my mistake - I missed it when you posted it the first time
0
 
jculkincysAuthor Commented:
may I ask why you have "$var" && $var?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.