1

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?

markp-fuso
  • 28,790
  • 4
  • 16
  • 36
  • 3
    in my system `ping` sends the error message to stderr; assuming `multipass` is not modifying this behavior, try redirecting stderr to stdout (`2>&1`), ie: `variable=$(multipass exec genesis -- ping -c 1 test.com 2>&1)` – markp-fuso Jul 05 '23 at 14:12
  • 1
    fwiw, the output shows the `ping` error is being sent to the terminal as opposed to being captured by the variable assignment (`variable=$( ...)`); adding `2>&1` on the end of the `multipass/ping` command should be sufficient to insure the variable assignment also captures anything send to stderr – markp-fuso Jul 05 '23 at 14:26

1 Answers1

1

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  
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134