How to search for substring in bash script output? If I searching in string directly it is working, but issue when searching in command output.

variable="ping: test.com: Name or service not known"

if [[ "$variable" =~ "not" ]]  
then
    echo "Failed"
else
    echo "Success"
fi  

This one is working.

But I am trying to do this:

variable=$(multipass exec genesis -- ping -c 1 test.com)

if [[ "$variable" =~ "not" ]]  
then
    echo "Failed"
else
    echo "Success"
fi  

But like this is not working...

Output in termninal:

$ sh test3.sh
ping: test.com: Name or service not known
Success

I am expecting to get Failed...

I guess I need somehow handle ping output in variable in different way?

1

There are 1 best solutions below

0
Diego Torres Milano On

Why parsing the output? There could be many other errors you won't catch. Do this instead.

#! /bin/bash

if multipass exec genesis -- ping -c 1 test.com; then
    echo "Success"
else
    echo "Failed"
fi