[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 12697
  • Last Modified:

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
0
jculkincys
Asked:
jculkincys
  • 5
  • 4
1 Solution
 
ravenplCommented:
if [ _$var = "_search text" ]; then
...
0
 
ravenplCommented:
posibly better
if [ "_$var" = "_search text" ]; then
0
 
jculkincysAuthor Commented:
Can you please explain a little what the underscore does?
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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
 
ravenplCommented:
I already have showed that. Haven't I?

if [[ -n "$var" && $var == *answer* ]]
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

Featured Post

Transaction-level recovery for Oracle database

Veeam Explore for Oracle delivers low RTOs and RPOs with agentless transaction log backup and transaction-level recovery of Oracle databases. You can restore the database to a precise point in time, even to a specific transaction.

  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now