14

I have a variable like below.

variable = This script is not found

if [[ "$variable" = ~ "not found" ]];
then
echo "Not Found"
else
echo "Its there"
if

while executing im getting below err,

line 4: syntax error in conditional expression
./test.sh: line 4: syntax error near `found"'
./test.sh: line 4: `if [[ "$variable" = ~ "not found" ]]; '

could anyone point me, What im missing here?

3
  • 2
    There should not be a space between = and ~. Write as =~ Commented Feb 27, 2013 at 17:57
  • Have tried that before. But got other err line 4: conditional binary operator expected ./test.sh: line 4: syntax error near =~' ./test.sh: line 4: if [[ "$variable" =~ "not found" ]]; ' Commented Feb 27, 2013 at 17:59
  • 1
    what happens if you change your assigment at the top to variable="This script is not found" ? Good luck. Commented Feb 27, 2013 at 18:15

5 Answers 5

30
LIST="some string with a substring you want to match"
SOURCE="substring"

if echo "$LIST" | grep -q "$SOURCE"; then
    echo "matched";
else
    echo "no match";
fi

Good Luck ;)

Sign up to request clarification or add additional context in comments.

Comments

10

Compare this with your version at the indicated points:

variable="This script is not found"  # <--

if [[ "$variable" =~ "not found" ]]  # <--
then
    echo "Not Found"
else
    echo "Its there"
fi  # <--

You can't put spaces around = in an assignment, and you need to quote a string literal that has spaces. You don't need a trailing ; if you're going to put then on its own line. And an if-then ends with "fi" not "if".

Comments

3

here is a correct construction of your if statement

if [[ "$variable" =~ "not found" ]]; then
      echo "Not Found";
else
      echo "Its there";
fi

Comments

0

Input:

line="There\'s a substring to be found!"

if [[ "$line" =~ *"substring"* ]]; then
    echo "Not Found";
else
    echo "Found!"
fi

Output:

Found!

Comments

-1

I have tried below codes which always return same result either in true or false

if [[ "$variable" =~ "not found" ]]; then
      echo "Not Found";
else
      echo "Its there";
fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.